import sys
from types import SimpleNamespace

import pytest

import project_brain.__main__ as cli
from project_brain.build.builder import GraphBuildError
from project_brain.cli.format import format_result
from project_brain.config import ConfigError


def test_main_rejects_file_as_project_path_without_traceback(
    tmp_path, monkeypatch, capsys,
):
    project_file = tmp_path / "not-a-directory"
    project_file.write_text("content", encoding="utf-8")
    monkeypatch.setattr(
        sys,
        "argv",
        ["project-brain", "--project", str(project_file), "info"],
    )

    with pytest.raises(SystemExit) as exc_info:
        cli.main()

    captured = capsys.readouterr()
    assert exc_info.value.code == 1
    assert "Project path is not a directory" in captured.err
    assert "Traceback" not in captured.out + captured.err


@pytest.mark.parametrize(
    ("error", "expected"),
    [
        (ConfigError("broken config"), "Invalid project configuration"),
        (GraphBuildError("build stopped"), "build stopped"),
    ],
)
def test_main_reports_expected_command_errors_without_traceback(
    tmp_path, monkeypatch, capsys, error, expected,
):
    def fail_info(_project_path):
        raise error

    monkeypatch.setattr(cli, "_cmd_info", fail_info)
    monkeypatch.setattr(
        sys,
        "argv",
        ["project-brain", "--project", str(tmp_path), "info"],
    )

    with pytest.raises(SystemExit) as exc_info:
        cli.main()

    captured = capsys.readouterr()
    assert exc_info.value.code == 2
    assert expected in captured.err
    assert "Traceback" not in captured.out + captured.err


def test_build_rejects_unsafe_stored_content_pattern_before_writing_config(
    tmp_path,
):
    args = SimpleNamespace(
        semantic=False,
        index_body=False,
        precision=None,
        store_doc_content=["../outside.md"],
    )

    with pytest.raises(ConfigError, match=r"stored_content.*\.\."):
        cli._cmd_build(tmp_path, args)

    assert not (tmp_path / ".botbrain" / "config.yaml").exists()


def test_failed_build_does_not_persist_new_stored_content_policy(tmp_path):
    docs = tmp_path / "docs"
    docs.mkdir()
    (docs / "large.md").write_text("# Large\n" + ("x" * 100), encoding="utf-8")
    from project_brain.config import Config

    config = Config.default()
    config.document_content_max_total_bytes = 1
    config.save(str(tmp_path))
    args = SimpleNamespace(
        semantic=False,
        index_body=False,
        precision=None,
        store_doc_content=["docs/**/*.md"],
    )

    with pytest.raises(GraphBuildError, match="max_total_bytes"):
        cli._cmd_build(tmp_path, args)

    assert Config.load(str(tmp_path)).document_content_include == []


def test_successful_build_persists_every_digest_affecting_cli_override(tmp_path):
    from project_brain.config import Config
    from project_brain.graph.generation import GenerationRepository
    from project_brain.watcher.reconciler import compute_graph_config_digest

    (tmp_path / "sample.py").write_text("def sample():\n    return 1\n", encoding="utf-8")
    # Use keyword strategy to avoid semantic index build in unit tests.
    pb_dir = tmp_path / ".botbrain"
    pb_dir.mkdir(exist_ok=True)
    (pb_dir / "config.yaml").write_text("search:\n  strategy: keyword\n", encoding="utf-8")
    args = SimpleNamespace(
        semantic=False,
        index_body=True,
        precision="full",
        store_doc_content=None,
    )

    cli._cmd_build(tmp_path, args)

    config = Config.load(str(tmp_path))
    assert config.index_body is True
    assert config.model_precision == "full"
    metadata = GenerationRepository(
        tmp_path / ".botbrain" / "graph"
    ).current_manifest()["metadata"]
    assert metadata["config_digest"] == compute_graph_config_digest(config)


@pytest.mark.parametrize(
    ("flags", "expected_refs", "expected_children"),
    [
        # No explicit flags -> None sentinel: the server resolves the
        # wiki.include_refs / wiki.include_children config defaults.
        ({}, None, None),
        ({"ref": True}, True, None),
        ({"child": True}, None, True),
        ({"ref": True, "child": True}, True, True),
        # Explicit negative legacy flags override everything.
        ({"ref": True, "no_ref": True}, False, None),
        ({"child": True, "no_child": True}, None, False),
        ({"ref": True, "no_ref": True, "child": True}, False, True),
    ],
)
def test_pull_wiki_cli_flag_mapping(
    monkeypatch, tmp_path, capsys, flags, expected_refs, expected_children,
):
    captured = {}

    class FakeServer:
        def __init__(self, _project_path):
            self.tool_names = ["pull_wiki"]

        def _ensure_initialized(self, start_watcher=False, read_only=False):
            pass

        def call_tool_sync(self, name, kwargs):
            captured["name"] = name
            captured["kwargs"] = kwargs
            return '{"url": "u"}'

        def close(self):
            pass

    from project_brain.mcp import server as server_module

    monkeypatch.setattr(server_module, "ProjectBrainServer", FakeServer)
    args = SimpleNamespace(
        url="https://wiki.huawei.com/domains/1/wiki/2",
        all=False,
        output=None,
        json=False,
        **{"ref": False, "no_ref": False, "child": False, "no_child": False,
           **flags},
    )

    cli._cmd_pull_wiki(tmp_path, args)

    assert captured["name"] == "pull_wiki"
    kwargs = captured["kwargs"]
    assert kwargs["include_refs"] is expected_refs
    assert kwargs["include_children"] is expected_children


def test_repl_recovers_from_unclosed_quote(monkeypatch, tmp_path, capsys):
    class FakeServer:
        def __init__(self, _project_path):
            self.mcp = SimpleNamespace(
                _tool_manager=SimpleNamespace(_tools={}),
            )

        def _ensure_initialized(self, start_watcher=False, read_only=False):
            assert start_watcher is False

    from project_brain.mcp import server as server_module

    monkeypatch.setattr(server_module, "ProjectBrainServer", FakeServer)
    monkeypatch.setattr(
        sys,
        "stdin",
        SimpleNamespace(isatty=lambda: False),
    )
    commands = iter(['search "unfinished', "quit"])
    monkeypatch.setattr("builtins.input", lambda *args: next(commands))

    cli._cmd_repl(tmp_path)

    captured = capsys.readouterr()
    assert "Invalid command syntax" in captured.out
    assert "Traceback" not in captured.out + captured.err


def test_human_diff_output_includes_payload_and_truncation():
    rendered = format_result(
        "get_change_diff",
        {
            "target": "abcdef12",
            "changes": [{
                "commit_sha": "abcdef123456",
                "file": "service.py",
                "change_type": "modified",
                "diff": "@@ -1 +1 @@\n-before\n+after\n",
            }],
            "truncated": True,
            "truncation_reason": "byte budget exhausted",
        },
        False,
    )

    assert "-before" in rendered
    assert "+after" in rendered
    assert "[truncated] byte budget exhausted" in rendered


def test_human_content_output_shows_source_and_continuation():
    rendered = format_result(
        "get_content",
        {
            "target": "doc_guide",
            "kind": "document",
            "file": "docs/guide.md",
            "line_start": 1,
            "line_end": 10,
            "source": "first page",
            "content_source": "graph",
            "truncated": True,
            "next_line_start": 1,
            "next_cursor": "char:64",
        },
        False,
    )

    assert "source: graph" in rendered
    assert "truncated: yes" in rendered
    assert "next_line_start: 1" in rendered
    assert "next_cursor: char:64" in rendered


def test_human_content_output_distinguishes_empty_and_unavailable():
    empty = format_result(
        "get_content",
        {"target": "doc_empty", "kind": "document", "source": ""},
        False,
    )
    unavailable = format_result(
        "get_content",
        {
            "target": "sec_converted",
            "kind": "section",
            "content": None,
            "content_unavailable_reason": (
                "converted_document_section_requires_graph_snapshot"
            ),
        },
        False,
    )

    assert "(empty content)" in empty
    assert "unavailable: converted_document_section" in unavailable


def test_human_keyword_search_output_includes_bounded_preview():
    rendered = format_result(
        "keyword_search",
        {
            "results": [{
                "score": 1.0,
                "name": "Stored guide",
                "file": "docs/guide.md",
                "line": 8,
                "content_preview": "the matching paragraph",
            }],
            "total": 1,
        },
        False,
    )

    assert "PREVIEW" in rendered
    assert "the matching paragraph" in rendered