import json
import subprocess
from pathlib import Path

REPO_ROOT = Path(__file__).resolve().parents[1]


def write_drill_proof(path: Path, *, status: str = "import_operation_done") -> None:
    path.write_text(
        json.dumps(
            {
                "status": status,
                "project_id": "teleo-501523",
                "cloudsql_instance": "teleo-pgvector-standby",
                "database": "teleo_kb",
                "postgres_schema": "teleo_restore",
                "source_sqlite_backup_sha256": "abc123",
                "source_table_count": 2,
                "source_total_rows": 4,
                "source_table_counts": {
                    "claims": 3,
                    "evidence": 1,
                },
            }
        )
    )


def run_verifier(drill_proof: Path, counts_csv: Path, output: Path) -> subprocess.CompletedProcess[str]:
    return subprocess.run(
        [
            "python3",
            "ops/verify_gcp_cloudsql_restore_readback.py",
            "--drill-proof",
            str(drill_proof),
            "--target-counts-csv",
            str(counts_csv),
            "--output",
            str(output),
        ],
        cwd=REPO_ROOT,
        text=True,
        capture_output=True,
        check=False,
    )


def test_cloudsql_restore_readback_passes_matching_counts(tmp_path: Path) -> None:
    proof = tmp_path / "drill.json"
    counts = tmp_path / "target-counts.csv"
    output = tmp_path / "verification.json"
    write_drill_proof(proof)
    counts.write_text("table_name,row_count\nclaims,3\nevidence,1\n")

    completed = run_verifier(proof, counts, output)

    assert completed.returncode == 0, completed.stderr
    payload = json.loads(output.read_text())
    assert payload["status"] == "pass"
    assert payload["source_table_count"] == 2
    assert payload["target_table_count"] == 2
    assert payload["source_total_rows"] == 4
    assert payload["target_total_rows"] == 4
    assert payload["mismatched_tables"] == []


def test_cloudsql_restore_readback_fails_mismatched_counts(tmp_path: Path) -> None:
    proof = tmp_path / "drill.json"
    counts = tmp_path / "target-counts.csv"
    output = tmp_path / "verification.json"
    write_drill_proof(proof)
    counts.write_text("table_name,row_count\nclaims,2\nevidence,1\n")

    completed = run_verifier(proof, counts, output)

    assert completed.returncode == 1
    payload = json.loads(output.read_text())
    assert payload["status"] == "fail"
    assert "total_rows source=4 target=3" in payload["problems"]
    assert payload["mismatched_tables"] == [
        {
            "source_rows": 3,
            "table": "claims",
            "target_rows": 2,
        }
    ]


def test_cloudsql_restore_readback_requires_completed_import(tmp_path: Path) -> None:
    proof = tmp_path / "drill.json"
    counts = tmp_path / "target-counts.csv"
    output = tmp_path / "verification.json"
    write_drill_proof(proof, status="prepared")
    counts.write_text("table_name,row_count\nclaims,3\nevidence,1\n")

    completed = run_verifier(proof, counts, output)

    assert completed.returncode == 1
    payload = json.loads(output.read_text())
    assert payload["status"] == "fail"
    assert "drill_status=prepared" in payload["problems"]
