"""Unit tests for the project_brain.wiki subpackage and pull_wiki integration.

These tests mock the network layer (requests session / wiki API) so they run
offline.  They cover URL parsing, cookie management, markdown conversion, the
PullResult contract, and the server-level pull_wiki tool's
pause→download→resume→update orchestration.
"""
from __future__ import annotations

import json
import os
import time
from unittest.mock import MagicMock

from project_brain.wiki import (
    PullResult,
    build_cookie_header,
    has_auth_cookies,
    load_cookies,
    parse_wiki_url_with_title,
    pull_wiki,
    resolve_cookie_file,
    save_cookies,
)
from project_brain.wiki.config import COOKIE_EXPIRE_SECONDS
from project_brain.wiki.markdown import html_to_markdown
from project_brain.wiki.processor import extract_wiki_links_from_text


# --------------------------------------------------------------------------
# URL parsing
# --------------------------------------------------------------------------

class TestParseWikiUrl:
    def test_url_with_sn(self):
        d, k, sn, t = parse_wiki_url_with_title(
            "https://wiki.huawei.com/domains/12345/wiki/67890/ABCDEF123"
        )
        assert d == "12345"
        assert k == "67890"
        assert sn == "ABCDEF123"
        assert t is None

    def test_url_with_sn_and_title_param(self):
        d, k, sn, t = parse_wiki_url_with_title(
            "https://wiki.huawei.com/domains/12345/wiki/67890/ABCDEF123?title=foo"
        )
        assert d == "12345" and k == "67890" and sn == "ABCDEF123"
        assert t == "foo"

    def test_url_without_sn(self):
        d, k, sn, t = parse_wiki_url_with_title(
            "https://wiki.huawei.com/domains/12345/wiki/67890"
        )
        assert d == "12345" and k == "67890" and sn is None

    def test_url_without_sn_trailing_slash(self):
        d, k, sn, t = parse_wiki_url_with_title(
            "https://wiki.huawei.com/domains/12345/wiki/67890/"
        )
        assert d == "12345" and k == "67890" and sn is None

    def test_invalid_url(self):
        d, k, sn, t = parse_wiki_url_with_title("https://example.com/foo")
        assert d is None and k is None and sn is None and t is None


# --------------------------------------------------------------------------
# Cookie management
# --------------------------------------------------------------------------

class TestCookies:
    def test_resolve_cookie_file_default(self, tmp_path, monkeypatch):
        # 隔离真实家目录:既有 ~/.projectbrain cookie 的机器上,
        # 解析结果会按设计回退到旧路径。
        import project_brain.wiki.config as wiki_config

        empty_home = tmp_path / "home"
        empty_home.mkdir()
        monkeypatch.setattr(
            wiki_config.Path, "home", lambda: empty_home, raising=False,
        )
        path = resolve_cookie_file(None)
        assert path.endswith("wiki_cookies.json")
        assert ".botbrain" in path

    def test_resolve_cookie_file_explicit(self, tmp_path):
        f = str(tmp_path / "my_cookies.json")
        assert resolve_cookie_file(f) == f

    def test_save_and_load_cookies(self, tmp_path):
        f = str(tmp_path / "cookies.json")
        cookies = [{"name": "w3_token", "value": "abc", "domain": ".huawei.com", "path": "/"}]
        save_cookies(cookies, f)
        assert os.path.exists(f)
        loaded = load_cookies(f)
        assert loaded == cookies

    def test_load_old_cookies_not_time_expired(self, tmp_path):
        """Cookies are no longer rejected by a hard-coded time expiry.

        The 20-minute expiry was removed because W3 SSO tokens last much
        longer.  An old cookie file should still load (actual expiry is
        detected by API 403, not by timestamp).
        """
        f = str(tmp_path / "cookies.json")
        data = {"saved_at": time.time() - 999999, "cookies": [
            {"name": "SESSION", "value": "abc", "domain": "wiki.huawei.com", "path": "/"},
        ]}
        with open(f, "w") as fh:
            json.dump(data, fh)
        loaded = load_cookies(f)
        assert loaded is not None
        assert len(loaded) == 1

    def test_load_missing_file(self, tmp_path):
        assert load_cookies(str(tmp_path / "nonexistent.json")) is None

    def test_has_auth_cookies(self):
        assert has_auth_cookies([{"name": "w3_token", "value": "x"}]) is True
        assert has_auth_cookies([{"name": "irrelevant", "value": "x"}]) is False
        assert has_auth_cookies(None) is False
        assert has_auth_cookies([]) is False

    def test_build_cookie_header(self, tmp_path):
        f = str(tmp_path / "cookies.json")
        save_cookies([{"name": "a", "value": "1"}, {"name": "b", "value": "2"}], f)
        header = build_cookie_header(f)
        assert "a=1" in header and "b=2" in header

    def test_build_cookie_header_empty(self, tmp_path):
        assert build_cookie_header(str(tmp_path / "none.json")) == ""


# --------------------------------------------------------------------------
# Markdown conversion
# --------------------------------------------------------------------------

class TestMarkdown:
    def test_basic_conversion(self):
        md = html_to_markdown("<h1>Title</h1><p>Hello <strong>world</strong></p>")
        assert "# Title" in md
        assert "**world**" in md

    def test_lists(self):
        md = html_to_markdown("<ul><li>a</li><li>b</li></ul>")
        assert "- a" in md and "- b" in md

    def test_code_block(self):
        html = "<pre><code>print('hi')</code></pre>"
        md = html_to_markdown(html)
        assert "```" in md
        assert "print('hi')" in md

    def test_table(self):
        html = "<table><tr><th>A</th><th>B</th></tr><tr><td>1</td><td>2</td></tr></table>"
        md = html_to_markdown(html)
        assert "|" in md
        assert "A" in md and "1" in md

    def test_empty_input(self):
        assert html_to_markdown("") == ""

    def test_links_and_images(self):
        html = '<a href="http://x/y">link</a><img src="z.png" alt="pic">'
        md = html_to_markdown(html)
        assert "[link](http://x/y)" in md
        assert "![pic](z.png)" in md


# --------------------------------------------------------------------------
# Wiki link extraction
# --------------------------------------------------------------------------

class TestExtractLinks:
    def test_extract_simple(self):
        text = "See https://wiki.huawei.com/domains/1/wiki/2/ABCDEF123 for details"
        links = extract_wiki_links_from_text(text)
        assert ("ABCDEF123", "https://wiki.huawei.com/domains/1/wiki/2/ABCDEF123") in links

    def test_exclude_title_param(self):
        text = "https://wiki.huawei.com/domains/1/wiki/2/ABCDEF123?title=foo"
        links = extract_wiki_links_from_text(text)
        assert links == []

    def test_no_links(self):
        assert extract_wiki_links_from_text("no links here") == []


# --------------------------------------------------------------------------
# PullResult contract
# --------------------------------------------------------------------------

class TestPullResult:
    def test_defaults(self):
        r = PullResult()
        assert r.success is False
        assert r.main_file is None
        assert r.files == []
        assert r.error is None

    def test_with_fields(self):
        r = PullResult(success=True, main_file="/tmp/a.md", files=["/tmp/a.md"], output_dir="/tmp")
        assert r.success is True
        assert r.main_file == "/tmp/a.md"
        assert r.files == ["/tmp/a.md"]


# --------------------------------------------------------------------------
# pull_wiki high-level entry (mocked network)
# --------------------------------------------------------------------------

class TestPullWikiEntry:
    def test_invalid_url_returns_error(self, tmp_path):
        """Without a valid cookie the pull fails before URL parsing.

        The high-level entry tries ``ensure_login`` first; with no cookie and
        no playwright it returns a PullResult with an error (does not raise).
        """
        result = pull_wiki(
            "https://example.com/nope", str(tmp_path),
            cookie_file=str(tmp_path / "c.json"),
        )
        assert result.success is False
        assert result.error is not None

    def test_no_cookie_returns_error(self, tmp_path):
        """Without a valid cookie, ensure_login fails → pull_wiki returns error."""
        result = pull_wiki(
            "https://wiki.huawei.com/domains/1/wiki/2/ABCDEF123",
            str(tmp_path),
            cookie_file=str(tmp_path / "nonexistent.json"),
        )
        assert result.success is False
        assert result.error is not None

    def test_invalid_url_with_valid_cookie(self, tmp_path):
        """With a valid cookie but unparseable URL, returns a parse error."""
        f = str(tmp_path / "cookies.json")
        save_cookies([{"name": "w3_token", "value": "abc", "domain": ".huawei.com", "path": "/"}], f)
        result = pull_wiki(
            "https://example.com/nope", str(tmp_path), cookie_file=f,
        )
        assert result.success is False
        assert "无法解析" in (result.error or "")


# --------------------------------------------------------------------------
# Server-level pull_wiki tool orchestration (mocked wiki + watcher)
# --------------------------------------------------------------------------

class TestPullWikiTool:
    """Verify the pull_wiki tool pauses the watcher, downloads, resumes, and updates."""

    def _make_server(self, tmp_path):
        from project_brain.mcp.server import ProjectBrainServer
        from project_brain.mcp.options import ServerOptions

        (tmp_path / "main.py").write_text("def f():\n    pass\n", encoding="utf-8")
        opts = ServerOptions(transport="stdio")
        server = ProjectBrainServer(str(tmp_path), options=opts)
        server._ensure_initialized(start_watcher=False, read_only=False)
        server._register_tools()
        return server

    def test_pull_wiki_tool_orchestration_with_watcher(self, tmp_path):
        """When a watcher is running, pause→download→resume→update is exercised."""
        server = self._make_server(tmp_path)

        call_log: list[str] = []
        # _pause returns True to simulate a running watcher being paused.
        server._pause_file_watcher = lambda: (call_log.append("pause"), True)[1]
        server._resume_file_watcher = lambda: (call_log.append("resume"), True)[1]

        updated_files: list[str] = []

        class _FakeUpdater:
            failed_paths: dict = {}
            semantic_dirty: bool = False

            def update(self, paths):
                updated_files.extend(paths)
                call_log.append(f"update:{len(paths)}")
                return len(paths)

        server._updater = _FakeUpdater()

        fake_files = [str(tmp_path / "docs" / "wiki" / "Doc" / "Doc.md")]
        fake_result = PullResult(
            success=True, main_file=fake_files[0],
            files=fake_files, output_dir=str(tmp_path / "docs" / "wiki"),
        )

        import project_brain.wiki
        original = project_brain.wiki.pull_wiki
        project_brain.wiki.pull_wiki = MagicMock(return_value=fake_result)
        try:
            raw = server.call_tool_sync("pull_wiki", {
                "url": "https://wiki.huawei.com/domains/1/wiki/2/ABCDEF123",
            })
        finally:
            project_brain.wiki.pull_wiki = original

        import json as _json
        result = _json.loads(raw)
        assert result["downloaded_count"] == 1
        assert result["graph_updated_files"] == 1
        # Ordering: pause → update → resume.
        pause_idx = call_log.index("pause")
        update_idx = next(i for i, c in enumerate(call_log) if c.startswith("update:"))
        resume_idx = call_log.index("resume")
        assert pause_idx < update_idx < resume_idx
        assert len(updated_files) == 1
        server.close()

    def test_pull_wiki_tool_no_watcher_skips_resume(self, tmp_path):
        """CLI mode: no watcher running, pause returns False, resume is skipped."""
        server = self._make_server(tmp_path)

        call_log: list[str] = []
        server._pause_file_watcher = lambda: (call_log.append("pause"), False)[1]
        server._resume_file_watcher = lambda: (call_log.append("resume"), True)[1]

        class _FakeUpdater:
            failed_paths: dict = {}
            semantic_dirty: bool = False

            def update(self, paths):
                call_log.append(f"update:{len(paths)}")
                return len(paths)

        server._updater = _FakeUpdater()

        fake_result = PullResult(
            success=True, main_file="/tmp/a.md", files=["/tmp/a.md"], output_dir="/tmp",
        )
        import project_brain.wiki
        original = project_brain.wiki.pull_wiki
        project_brain.wiki.pull_wiki = MagicMock(return_value=fake_result)
        try:
            raw = server.call_tool_sync("pull_wiki", {
                "url": "https://wiki.huawei.com/domains/1/wiki/2/ABCDEF123",
            })
        finally:
            project_brain.wiki.pull_wiki = original

        import json as _json
        result = _json.loads(raw)
        assert result["downloaded_count"] == 1
        # No resume because pause returned False (no watcher was running).
        assert "resume" not in call_log
        server.close()

    def test_pull_wiki_tool_handles_download_error(self, tmp_path):
        """If the wiki pull fails, the tool still resumes the watcher and reports error."""
        server = self._make_server(tmp_path)

        call_log: list[str] = []
        server._pause_file_watcher = lambda: (call_log.append("pause"), True)[1]
        server._resume_file_watcher = lambda: (call_log.append("resume"), True)[1]
        server._updater = None

        bad_result = PullResult(success=False, error="connection refused")
        import project_brain.wiki
        original = project_brain.wiki.pull_wiki
        project_brain.wiki.pull_wiki = MagicMock(return_value=bad_result)
        try:
            raw = server.call_tool_sync("pull_wiki", {
                "url": "https://wiki.huawei.com/domains/1/wiki/2/ABCDEF123",
            })
        finally:
            project_brain.wiki.pull_wiki = original

        import json as _json
        result = _json.loads(raw)
        assert result["error"] == "connection refused"
        assert result["downloaded_count"] == 0
        # Watcher resumed even on failure (was_watching=True).
        assert "resume" in call_log
        server.close()


class TestPullWikiToolConfigDefaults:
    """None include args fall back to wiki.include_* config; explicit args win."""

    def test_config_defaults_and_explicit_override(self, tmp_path):
        pb_dir = tmp_path / ".botbrain"
        pb_dir.mkdir()
        (pb_dir / "config.yaml").write_text(
            "wiki:\n  include_refs: true\n  include_children: true\n",
            encoding="utf-8",
        )
        (tmp_path / "main.py").write_text("def f():\n    pass\n", encoding="utf-8")

        from project_brain.mcp.server import ProjectBrainServer
        from project_brain.mcp.options import ServerOptions

        opts = ServerOptions(transport="stdio")
        server = ProjectBrainServer(str(tmp_path), options=opts)
        server._ensure_initialized(start_watcher=False, read_only=False)
        server._register_tools()

        fake_result = PullResult(success=True, files=[], output_dir="docs/wiki")
        captured = {}

        def _spy(url, out, **kwargs):
            captured.update(kwargs)
            return fake_result

        import project_brain.wiki
        original = project_brain.wiki.pull_wiki
        project_brain.wiki.pull_wiki = _spy
        try:
            server.call_tool_sync("pull_wiki", {"url": "https://x/1/2/ABC"})
            assert captured["include_refs"] is True
            assert captured["include_children"] is True

            server.call_tool_sync(
                "pull_wiki",
                {"url": "https://x/1/2/ABC", "include_children": False},
            )
            assert captured["include_refs"] is True
            assert captured["include_children"] is False
        finally:
            project_brain.wiki.pull_wiki = original
        server.close()


# --------------------------------------------------------------------------
# query_children_by_sn pagination
# --------------------------------------------------------------------------

class TestQueryChildrenPagination:
    """query_children_by_sn must page past the single-page 50-child cap."""

    @staticmethod
    def _children(start, count):
        return [
            {"sn": f"SN{start + i:04d}", "title": f"child-{start + i}"}
            for i in range(count)
        ]

    @staticmethod
    def _payload(children):
        return {"wikiSubFile": {"children": children}}

    def _patch_api(self, monkeypatch, pages):
        """Patch processor.wiki_api_get to serve canned pages in order."""
        from project_brain.wiki import processor as processor_module

        calls: list[dict] = []

        def fake_api_get(session, domain_id, kanban_id, api_type, params=None, **kwargs):
            assert api_type == "children_wiki_by_sn"
            calls.append(dict(params))
            return pages[len(calls) - 1]

        monkeypatch.setattr(processor_module, "wiki_api_get", fake_api_get)
        return calls

    def test_multipage_accumulates_all_children(self, monkeypatch):
        page1 = self._payload(self._children(0, 50))
        page2 = self._payload(self._children(50, 30))
        calls = self._patch_api(monkeypatch, [page1, page2])

        from project_brain.wiki.processor import query_children_by_sn
        result = query_children_by_sn(object(), "d1", "k1", "SNROOT")

        assert len(result) == 80
        assert {c["sn"] for c in result} == {f"SN{i:04d}" for i in range(80)}
        assert calls[0]["page_num"] == 1
        assert calls[1]["page_num"] == 2

    def test_short_page_requires_single_call(self, monkeypatch):
        calls = self._patch_api(
            monkeypatch, [self._payload(self._children(0, 20))],
        )

        from project_brain.wiki.processor import query_children_by_sn
        result = query_children_by_sn(object(), "d1", "k1", "SNROOT")

        assert len(result) == 20
        assert len(calls) == 1

    def test_duplicate_page_stops_without_looping(self, monkeypatch):
        same = self._payload(self._children(0, 50))
        calls = self._patch_api(monkeypatch, [same, same, same])

        from project_brain.wiki.processor import query_children_by_sn
        result = query_children_by_sn(object(), "d1", "k1", "SNROOT")

        assert len(result) == 50
        assert len(calls) == 2

    def test_first_page_failure_returns_none(self, monkeypatch):
        self._patch_api(monkeypatch, [None])

        from project_brain.wiki.processor import query_children_by_sn
        assert query_children_by_sn(object(), "d1", "k1", "SNROOT") is None

    def test_later_page_failure_returns_partial(self, monkeypatch):
        page1 = self._payload(self._children(0, 50))
        calls = self._patch_api(monkeypatch, [page1, None])

        from project_brain.wiki.processor import query_children_by_sn
        result = query_children_by_sn(object(), "d1", "k1", "SNROOT")

        assert len(result) == 50

    def test_overlapping_pages_deduplicate(self, monkeypatch):
        page1 = self._payload(self._children(0, 50))
        # Second page (not full) returns an overlapping window plus new items.
        overlap = self._children(40, 20) + self._children(60, 25)
        self._patch_api(monkeypatch, [page1, self._payload(overlap)])

        from project_brain.wiki.processor import query_children_by_sn
        result = query_children_by_sn(object(), "d1", "k1", "SNROOT")

        sns = [c["sn"] for c in result]
        assert len(sns) == len(set(sns))
        assert {f"SN{i:04d}" for i in range(85)} == set(sns)