from __future__ import annotations

import sys
from pathlib import Path

from click.testing import CliRunner

sys.path.insert(0, str(Path(__file__).parent))
from conftest import git_init, index_in_process, invoke_cli, parse_json_output

from roam.commands.cmd_verify import SEVERITY_WARN, _check_claims


def test_check_claims_flags_specific_unsupported_claims(tmp_path: Path):
    doc = tmp_path / "README.md"
    doc.write_text(
        "\n".join(
            [
                "Roam is the fastest local code intelligence tool.",
                "It has 267 commands and 243 tools.",
            ]
        ),
        encoding="utf-8",
    )

    result = _check_claims(["README.md"], tmp_path)

    assert result["advisory"] is True
    assert result["claims_checked"] == 2
    assert [v["severity"] for v in result["violations"]] == [SEVERITY_WARN, SEVERITY_WARN]
    assert all(v["category"] == "claims" for v in result["violations"])


def test_check_claims_skips_sourced_and_fenced_claims(tmp_path: Path):
    doc = tmp_path / "README.md"
    doc.write_text(
        "\n".join(
            [
                "As of 2026-06-12, benchmark measured 267 commands.",
                "```bash",
                "echo '100% synthetic fixture text'",
                "```",
            ]
        ),
        encoding="utf-8",
    )

    result = _check_claims(["README.md"], tmp_path)

    assert result["claims_checked"] == 1
    assert result["violations"] == []


def test_check_claims_accepts_adjacent_evidence_sidecar(tmp_path: Path):
    doc = tmp_path / "README.md"
    doc.write_text(
        "\n".join(
            [
                "Roam has 267 commands and 243 tools.",
                "Evidence: generated by `roam surface --json` on 2026-06-13.",
            ]
        ),
        encoding="utf-8",
    )

    result = _check_claims(["README.md"], tmp_path)

    assert result["claims_checked"] == 1
    assert result["violations"] == []


def test_check_claims_accepts_table_evidence_caption(tmp_path: Path):
    doc = tmp_path / "README.md"
    doc.write_text(
        "\n".join(
            [
                "Benchmark measured on 2026-06-13 with n=3 cells.",
                "",
                "| Metric | Value |",
                "|---|---|",
                "| Cost | $1.30 |",
                "| Wall time | 10 seconds |",
            ]
        ),
        encoding="utf-8",
    )

    result = _check_claims(["README.md"], tmp_path)

    assert result["claims_checked"] == 3
    assert result["violations"] == []


def test_check_claims_accepts_table_evidence_footnote(tmp_path: Path):
    doc = tmp_path / "README.md"
    doc.write_text(
        "\n".join(
            [
                "| Metric | Value |",
                "|---|---|",
                "| Cost | $1.30 |",
                "| Wall time | 10 seconds |",
                "",
                "Evidence: benchmark measured on 2026-06-13 with n=3 cells.",
            ]
        ),
        encoding="utf-8",
    )

    result = _check_claims(["README.md"], tmp_path)

    assert result["claims_checked"] == 3
    assert result["violations"] == []


def test_check_claims_skips_historical_changelog(tmp_path: Path):
    doc = tmp_path / "CHANGELOG.md"
    doc.write_text("Release note: shipped 267 commands and 243 tools.\n", encoding="utf-8")

    result = _check_claims(["CHANGELOG.md"], tmp_path)

    assert result["claims_checked"] == 0
    assert result["violations"] == []


def test_check_claims_skips_unhinted_prompt_txt_files(tmp_path: Path):
    doc = tmp_path / "prompt.txt"
    doc.write_text(
        "- Pricing section: 3 tiers (Free, Pro $12/mo, Enterprise $49/mo)\n",
        encoding="utf-8",
    )

    result = _check_claims(["prompt.txt"], tmp_path)

    assert result["claims_checked"] == 0
    assert result["violations"] == []


def test_check_claims_skips_outline_headings_and_template_placeholders(tmp_path: Path):
    doc = tmp_path / "README.md"
    doc.write_text(
        "\n".join(
            [
                "### 4.3 Test to code reach",
                "> What we found: [top 3 findings].",
                '<a href="mailto:hello@example.com?subject=Roam%20Cloud">Email</a>',
                "Roam has 267 commands.",
            ]
        ),
        encoding="utf-8",
    )

    result = _check_claims(["README.md"], tmp_path)

    assert result["claims_checked"] == 1
    assert len(result["violations"]) == 1
    assert "267 commands" in result["violations"][0]["message"]


def test_verify_claims_json_discloses_non_code_scope(tmp_path: Path, monkeypatch):
    repo = tmp_path / "repo"
    repo.mkdir()
    (repo / ".gitignore").write_text(".roam/\n", encoding="utf-8")
    (repo / "README.md").write_text("Roam is the fastest local code intelligence tool.\n", encoding="utf-8")
    git_init(repo)
    monkeypatch.chdir(repo)
    out, rc = index_in_process(repo, "--force")
    assert rc == 0, out

    result = invoke_cli(CliRunner(), ["verify", "--checks", "claims", "README.md"], cwd=repo, json_mode=True)
    envelope = parse_json_output(result)

    assert result.exit_code == 0
    assert envelope["summary"]["verdict"] == "PASS"
    assert envelope["summary"]["scope"]["non_code_file_count"] == 1
    assert envelope["categories"]["claims"]["violation_count"] == 1


def test_verify_report_includes_claim_surfaces_by_default(tmp_path: Path, monkeypatch):
    repo = tmp_path / "repo"
    repo.mkdir()
    (repo / ".gitignore").write_text(".roam/\n", encoding="utf-8")
    (repo / "app.py").write_text("def helper():\n    return 1\n", encoding="utf-8")
    (repo / "README.md").write_text("Roam is the only tool that compiles local proof bundles.\n", encoding="utf-8")
    git_init(repo)
    monkeypatch.chdir(repo)
    out, rc = index_in_process(repo, "--force")
    assert rc == 0, out

    result = invoke_cli(CliRunner(), ["verify", "--report", "--checks", "claims"], cwd=repo, json_mode=True)
    envelope = parse_json_output(result)

    assert result.exit_code == 0
    assert envelope["summary"]["scope"]["non_code_file_count"] >= 1
    assert envelope["categories"]["claims"]["violation_count"] == 1
