import json
import os
import sqlite3
import subprocess


def test_gcp_cloudsql_restore_drill_dry_run(tmp_path):
    db_path = tmp_path / "source.db"
    conn = sqlite3.connect(db_path)
    conn.execute("create table response_audit (id integer primary key, query text)")
    conn.execute("insert into response_audit (query) values (?)", ("hello",))
    conn.commit()
    conn.close()

    proof_root = tmp_path / "proofs"
    output_root = tmp_path / "private"
    env = {
        **os.environ,
        "SQLITE_BACKUP": str(db_path),
        "OUTPUT_ROOT": str(output_root),
        "PROOF_ROOT": str(proof_root),
        "TS": "20260707Tdryrun",
        "PROJECT_ID": "teleo-501523",
        "INSTANCE": "teleo-pgvector-standby",
        "DATABASE": "teleo_kb",
    }
    result = subprocess.run(
        ["bash", "ops/run_gcp_cloudsql_restore_drill.sh"],
        check=True,
        capture_output=True,
        text=True,
        env=env,
    )

    payload = json.loads(result.stdout)
    assert payload["mode"] == "dry_run"
    assert payload["source_table_count"] == 1
    assert payload["source_total_rows"] == 1

    proof = json.loads((proof_root / "gcp-cloudsql-restore-drill-20260707Tdryrun.json").read_text())
    assert proof["status"] == "prepared"
    assert proof["gcs_import_uri"].startswith("gs://teleo-501523-prod-backups/")
    assert proof["source_table_counts"] == {"response_audit": 1}
    assert "gcloud sql import sql" in "\n".join(proof["planned_commands"])
    assert (output_root / "gcp-cloudsql-restore-drill-20260707Tdryrun" / "target-counts.sql").exists()
