from __future__ import annotations

from types import SimpleNamespace
from unittest.mock import MagicMock

import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient

from agency.configs.agconfig import agconfig
from agency.harness.adapters.claude_code import ClaudeCodeAdapter
from agency.harness.adapters.codex import CodexAdapter
from agency.harness.adapters.grok import GrokAdapter
from agency.harness.adapters.native import NativeAdapter
from agency.harness.adapters.opencode import OpenCodeAdapter


@pytest.mark.parametrize(
    "backend_cls", [ClaudeCodeAdapter, CodexAdapter, GrokAdapter, OpenCodeAdapter]
)
def test_external_stream_only_emits_authoritative_text_after_redirect(backend_cls):
    stream = [
        {"type": "delta", "content": "superseded draft"},
        {
            "type": "done",
            "message": {
                "role": "assistant",
                "blocks": [{"type": "text", "index": 0, "text": "authoritative final"}],
            },
            "stop_reason": "stop",
            "usage": {},
        },
    ]
    frames = "".join(backend_cls(agconfig())._format_agency_stream_to_harness(iter(stream), "m"))
    assert "superseded draft" not in frames
    assert "authoritative final" in frames


@pytest.mark.parametrize(
    ("backend_cls", "path"),
    [
        (ClaudeCodeAdapter, "/v1/messages"),
        (CodexAdapter, "/v1/responses"),
        (GrokAdapter, "/v1/chat/completions"),
        (NativeAdapter, "/v1/chat/completions"),
        (OpenCodeAdapter, "/v1/chat/completions"),
    ],
)
def test_registered_adapter_routes_inject_fastapi_request(backend_cls, path):
    app = FastAPI()
    bridge = SimpleNamespace(validate_token=lambda _token: False)
    backend_cls(agconfig()).register(app, bridge)

    with TestClient(app) as client:
        response = client.post(path, json={})

    assert response.status_code == 401
    assert "unknown or missing bearer token" in response.text


@pytest.mark.parametrize("stream", [False, True])
@pytest.mark.parametrize("title_format", ["legacy", "session_tags"])
def test_claude_session_title_request_is_answered_without_model_dispatch(stream, title_format):
    app = FastAPI()
    bridge = SimpleNamespace(
        validate_token=lambda _token: True,
        resolve_model=lambda _token: "test-model",
        dispatch=MagicMock(side_effect=AssertionError("title request reached the model")),
        dispatch_stream=MagicMock(side_effect=AssertionError("title request reached the model")),
        log_warning=MagicMock(),
    )
    ClaudeCodeAdapter(agconfig()).register(app, bridge)
    body = {
        "stream": stream,
        "messages": [
            {
                "role": "user",
                "content": (
                    "Generate a concise, sentence-case title (3-7 words) "
                    "that captures the main topic of this coding session."
                ),
            }
        ],
    }
    if title_format == "session_tags":
        # Claude Code 2.1.251 moved the title instructions into the system
        # prompt and wraps the real invocation input as data, not a model turn.
        body["system"] = (
            "The session content is provided inside <session> tags. "
            'Return JSON with a single "title" field. Capitalize the first letter of the title.'
        )
        body["messages"] = [{"role": "user", "content": "<session>Fix a bug</session>"}]

    with TestClient(app) as client:
        response = client.post("/v1/messages", headers={"x-api-key": "token"}, json=body)

    assert response.status_code == 200
    assert "Agency session" in response.text
    bridge.dispatch.assert_not_called()
    bridge.dispatch_stream.assert_not_called()


@pytest.mark.parametrize("stream", [False, True])
@pytest.mark.parametrize("auxiliary", ["title", "dashboard"])
def test_grok_auxiliary_request_is_answered_without_model_dispatch(stream, auxiliary):
    app = FastAPI()
    bridge = SimpleNamespace(
        validate_token=lambda _token: True,
        resolve_model=lambda _token: "test-model",
        dispatch=MagicMock(side_effect=AssertionError("title request reached the model")),
        dispatch_stream=MagicMock(side_effect=AssertionError("title request reached the model")),
    )
    GrokAdapter(agconfig()).register(app, bridge)
    body = {
        "stream": stream,
        "messages": [
            {
                "role": "system",
                "content": (
                    "You are tasked with generating the session title.\n"
                    "Just generate the session_title and nothing else"
                ),
            },
            {"role": "user", "content": "<user_query>Fix a bug</user_query>"},
        ],
    }
    if auxiliary == "dashboard":
        body["messages"] = [
            {"role": "assistant", "content": "The actual answer"},
            {
                "role": "user",
                "content": (
                    "<system-reminder>Write an ultra-short dashboard line that captures "
                    "the AGENT'S REPLY for the last turn only — a summary.</system-reminder>"
                ),
            },
        ]
    with TestClient(app) as client:
        response = client.post(
            "/v1/chat/completions", headers={"Authorization": "Bearer token"}, json=body
        )
    assert response.status_code == 200
    assert ("Agency session" if auxiliary == "title" else "Agency turn") in response.text
    bridge.dispatch.assert_not_called()
    bridge.dispatch_stream.assert_not_called()


def test_codex_disconnect_before_first_frame_closes_upstream():
    import asyncio
    import json

    async def exercise():
        started = asyncio.Event()
        closed = asyncio.Event()

        async def stream(*args):
            try:
                started.set()
                await asyncio.Event().wait()
                yield {}
            finally:
                closed.set()

        app = FastAPI()
        bridge = SimpleNamespace(
            validate_token=lambda token: True,
            resolve_model=lambda token: "test-model",
            dispatch_stream_async=stream,
        )
        CodexAdapter(agconfig()).register(app, bridge)
        body = json.dumps({"stream": True, "input": "test cancellation"}).encode()
        sent_body = False
        responses = []

        async def receive():
            nonlocal sent_body
            if not sent_body:
                sent_body = True
                return {"type": "http.request", "body": body, "more_body": False}
            await started.wait()
            return {"type": "http.disconnect"}

        async def send(message):
            responses.append(message)

        scope = {
            "type": "http",
            "asgi": {"version": "3.0"},
            "http_version": "1.1",
            "method": "POST",
            "scheme": "http",
            "path": "/v1/responses",
            "raw_path": b"/v1/responses",
            "query_string": b"",
            "headers": [(b"authorization", b"Bearer test"), (b"content-type", b"application/json")],
            "client": ("127.0.0.1", 1),
            "server": ("127.0.0.1", 80),
        }
        task = asyncio.create_task(app(scope, receive, send))
        try:
            await asyncio.wait_for(started.wait(), 2)
            await asyncio.wait_for(closed.wait(), 2)
            await asyncio.wait_for(task, 2)
            assert responses[0]["status"] == 499
        finally:
            task.cancel()
            await asyncio.gather(task, return_exceptions=True)

    asyncio.run(exercise())


@pytest.mark.parametrize(
    ("backend_cls", "path", "body"),
    [
        (
            ClaudeCodeAdapter,
            "/v1/messages",
            {"model": "m", "max_tokens": 8, "messages": [{"role": "user", "content": "hi"}]},
        ),
        (CodexAdapter, "/v1/responses", {"model": "m", "input": "hi"}),
        (
            GrokAdapter,
            "/v1/chat/completions",
            {"model": "m", "messages": [{"role": "user", "content": "hi"}]},
        ),
        (
            NativeAdapter,
            "/v1/chat/completions",
            {"model": "m", "messages": [{"role": "user", "content": "hi"}]},
        ),
        (
            OpenCodeAdapter,
            "/v1/chat/completions",
            {"model": "m", "messages": [{"role": "user", "content": "hi"}]},
        ),
    ],
)
def test_non_stream_dispatch_does_not_block_the_event_loop(backend_cls, path, body):
    import asyncio
    import threading

    import httpx

    released = threading.Event()
    seen: list = []

    def dispatch(_token, _ctx):
        seen.append(released.wait(5))
        return {
            "type": "done",
            "message": {
                "role": "assistant",
                "blocks": [{"type": "text", "index": 0, "text": "ok"}],
            },
            "stop_reason": "stop",
            "usage": {"prompt_tokens": 0, "completion_tokens": 0},
        }

    app = FastAPI()
    app.get("/release")(lambda: released.set())
    bridge = SimpleNamespace(
        validate_token=lambda _token: True,
        resolve_model=lambda _token: "m",
        dispatch=dispatch,
    )
    backend_cls(agconfig()).register(app, bridge)

    async def run():
        transport = httpx.ASGITransport(app=app)
        async with httpx.AsyncClient(transport=transport, base_url="http://t") as client:
            pending = asyncio.create_task(
                client.post(path, json=body, headers={"Authorization": "Bearer t"})
            )
            await asyncio.sleep(0.2)
            await client.get("/release")
            return await pending

    response = asyncio.run(run())
    assert response.status_code == 200, response.text
    assert seen == [True]
