"""Tests for the Research (deep Q&A) API endpoints."""

import pytest
from httpx import AsyncClient


@pytest.mark.asyncio
class TestResearchEndpoint:
    """POST /api/v1/research — SSE streaming research answers."""

    async def test_research_plan_requires_auth(self, client: AsyncClient, api_prefix: str):
        resp = await client.post(
            f"{api_prefix}/research/plan",
            json={
                "task": {
                    "topic": "数字政府建设",
                    "question": "数字政府建设的主要目标是什么？",
                    "output_template": "comprehensive",
                    "depth_level": "deep",
                },
            },
        )
        assert resp.status_code in (401, 403)

    async def test_research_plan_basic(self, client: AsyncClient, api_prefix: str, auth_headers: dict):
        resp = await client.post(
            f"{api_prefix}/research/plan",
            json={
                "task": {
                    "topic": "数字政府建设",
                    "question": "数字政府建设的主要目标是什么？",
                    "goal": "梳理目标和主要措施",
                    "output_template": "policy_brief",
                    "depth_level": "deep",
                },
            },
            headers=auth_headers,
        )
        assert resp.status_code == 200
        data = resp.json()
        assert data["plan"]["summary"]
        assert data["plan"]["section_outline"]

    async def test_research_requires_auth(self, client: AsyncClient, api_prefix: str):
        resp = await client.post(f"{api_prefix}/research", json={
            "question": "数字政府建设的主要目标是什么？",
        })
        assert resp.status_code in (401, 403)

    async def test_research_basic(self, client: AsyncClient, api_prefix: str, auth_headers: dict):
        """Research query should return SSE text/event-stream response."""
        resp = await client.post(
            f"{api_prefix}/research",
            json={"question": "数字政府建设的主要目标是什么？"},
            headers=auth_headers,
        )
        # SSE streams return 200 with text/event-stream content type
        assert resp.status_code == 200
        content_type = resp.headers.get("content-type", "")
        assert "text/event-stream" in content_type or resp.status_code == 200

    async def test_research_with_session(self, client: AsyncClient, api_prefix: str, auth_headers: dict):
        """Research query with session_id for multi-turn context."""
        resp = await client.post(
            f"{api_prefix}/research",
            json={
                "question": "清远市的发展规划有哪些？",
                "session_id": "test-session-001",
            },
            headers=auth_headers,
        )
        assert resp.status_code == 200

    async def test_research_run_basic(self, client: AsyncClient, api_prefix: str, auth_headers: dict):
        resp = await client.post(
            f"{api_prefix}/research/run",
            json={
                "task": {
                    "topic": "数字政府建设",
                    "question": "数字政府建设的主要目标是什么？",
                    "goal": "梳理目标和主要措施",
                    "output_template": "comprehensive",
                    "depth_level": "standard",
                },
                "plan": {
                    "summary": "围绕数字政府建设梳理目标、路径和执行要求。",
                    "objectives": ["归纳政策目标"],
                    "sub_questions": ["主要目标是什么？"],
                    "retrieval_focus": ["数字政府", "建设目标"],
                    "section_outline": ["研究结论", "政策依据"],
                    "expected_deliverables": ["执行摘要", "引用附录"],
                    "notes": [],
                    "included_doc_ids": [],
                    "included_matter_ids": [],
                },
            },
            headers=auth_headers,
        )
        assert resp.status_code == 200
        content_type = resp.headers.get("content-type", "")
        assert "text/event-stream" in content_type or resp.status_code == 200

    async def test_research_rerun_section_basic(
        self,
        client: AsyncClient,
        api_prefix: str,
        auth_headers: dict,
    ):
        resp = await client.post(
            f"{api_prefix}/research/sections/rerun",
            json={
                "task": {
                    "topic": "数字政府建设",
                    "question": "数字政府建设的主要目标是什么？",
                    "goal": "梳理目标和主要措施",
                    "output_template": "comprehensive",
                    "depth_level": "standard",
                },
                "plan": {
                    "summary": "围绕数字政府建设梳理目标、路径和执行要求。",
                    "objectives": ["归纳政策目标"],
                    "sub_questions": ["主要目标是什么？"],
                    "retrieval_focus": ["数字政府", "建设目标"],
                    "section_outline": ["研究结论", "政策依据"],
                    "expected_deliverables": ["执行摘要", "引用附录"],
                    "notes": [],
                    "included_doc_ids": [],
                    "included_matter_ids": [],
                },
                "section_title": "政策依据",
                "section_summary": "归纳主要政策依据与目标导向。",
                "source_doc_ids": [],
            },
            headers=auth_headers,
        )
        assert resp.status_code == 200
        content_type = resp.headers.get("content-type", "")
        assert "text/event-stream" in content_type or resp.status_code == 200
