"""Unit tests for Semantic Blast Radius & Documentation Invariants Analyzer."""
from __future__ import annotations

import json
import os
import subprocess
import sys
import pytest

PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
DOC_SCRIPT_PATH = os.path.join(PROJECT_ROOT, "tools", "analysis", "doc_blast_radius.py")
UNIFIED_SCRIPT_PATH = os.path.join(PROJECT_ROOT, "tools", "analysis", "blast_radius.py")


def run_doc_blast_radius(target: str, *extra_args: str) -> dict:
    """Helper to run doc_blast_radius.py and parse JSON output."""
    cmd = [sys.executable, DOC_SCRIPT_PATH, "--target", target, "--format", "json", *extra_args]
    result = subprocess.run(cmd, capture_output=True, text=True, cwd=PROJECT_ROOT, encoding="utf-8")
    assert result.returncode == 0, f"Script failed with stderr: {result.stderr}"
    return json.loads(result.stdout)


def run_unified_blast_radius(target: str, *extra_args: str) -> dict:
    """Helper to run unified blast_radius.py and parse JSON output."""
    cmd = [sys.executable, UNIFIED_SCRIPT_PATH, "--target", target, "--format", "json", *extra_args]
    result = subprocess.run(cmd, capture_output=True, text=True, cwd=PROJECT_ROOT, encoding="utf-8")
    assert result.returncode == 0, f"Script failed with stderr: {result.stderr}"
    return json.loads(result.stdout)


def test_doc_blast_radius_scratch_file_is_low_risk() -> None:
    """Scratch or design request files should be LOW risk and unblocked."""
    res = run_doc_blast_radius("docs/design_requests/templates/TEMPLATE.md")
    assert res["risk_level"] == "LOW"
    assert res["blocked"] is False


def test_doc_blast_radius_quest_specs_is_critical() -> None:
    """Quest specs in wiki/vi should be CRITICAL, detect Wiki Mirrors, Code Catalogs, and SQLite ties."""
    target = "wiki/vi/QUESTS_AND_MILESTONES_SPECS.md"
    res = run_doc_blast_radius(target)
    assert res["risk_level"] == "CRITICAL"
    assert len(res["all_affected_docs"]) > 10
    
    # Must detect multilingual counterparts
    assert any("wiki/en/QUESTS_AND_MILESTONES_SPECS.md" in d for d in res["multilingual_counterparts"])
    assert any("wiki/zh/QUESTS_AND_MILESTONES_SPECS.md" in d for d in res["multilingual_counterparts"])

    # Must detect code catalogs & services
    assert any("quest_catalog.py" in c or "quest_engine.py" in c for c in res["affected_code_catalogs"])

    # Must detect SQLite game matrix quests
    assert len(res["database_impacts"]) > 0


def test_doc_blast_radius_economy_specs_is_critical() -> None:
    """Core economy architecture doc must detect reverse references and currency catalogs."""
    target = "docs/game_design/ANTI_INFLATION_SAVAGE_ECONOMY_2026.md"
    res = run_doc_blast_radius(target)
    assert res["risk_level"] == "CRITICAL"
    assert len(res["reverse_dependent_docs"]) > 0
    assert any("ITEM_CRAFTING" in d or "ORIGINAL_SYSTEMS" in d for d in res["reverse_dependent_docs"])
    assert any("consignment_vault" in c or "economy" in c for c in res["affected_code_catalogs"])


def test_doc_blast_radius_acknowledgment_flow() -> None:
    """Acknowledging a document unlocks it."""
    target = "docs/standards/ENGINEERING_STANDARDS_2026.md"
    res_ack = run_doc_blast_radius(target, "--ack")
    assert res_ack["acknowledged"] is True
    assert res_ack["blocked"] is False

    # Immediate query confirms unlocked
    res_check = run_doc_blast_radius(target)
    assert res_check["acknowledged"] is True
    assert res_check["blocked"] is False


def test_unified_blast_radius_delegation() -> None:
    """blast_radius.py should automatically delegate to doc_blast_radius for .md files."""
    target = "wiki/vi/QUESTS_AND_MILESTONES_SPECS.md"
    res = run_unified_blast_radius(target)
    assert res["risk_level"] == "CRITICAL"
    assert "doc_details" in res
    assert len(res["affected_files"]) > 10
    assert len(res["domain_impacts"]) > 0
