from __future__ import annotations

import hashlib
import subprocess
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
SCRIPT = ROOT / "gitea-bundle-sample-restore-dry-run.sh"


def run(command: list[str], cwd: Path) -> subprocess.CompletedProcess[str]:
    return subprocess.run(command, cwd=cwd, text=True, capture_output=True, check=True)


def test_gitea_bundle_sample_restore_dry_run_writes_success_metric(tmp_path: Path) -> None:
    source = tmp_path / "source"
    bundle_root = tmp_path / "bundles"
    textfile = tmp_path / "gitea_bundle_restore_dry_run.prom"
    source.mkdir()
    bundle_root.mkdir()

    run(["git", "init", "-q"], source)
    run(["git", "config", "user.email", "codex@example.invalid"], source)
    run(["git", "config", "user.name", "Codex"], source)
    (source / "README.md").write_text("restore dry-run\n", encoding="utf-8")
    run(["git", "add", "README.md"], source)
    run(["git", "commit", "-q", "-m", "seed"], source)
    bundle = bundle_root / "wooo__awoooi.bundle"
    run(["git", "bundle", "create", str(bundle), "--all"], source)
    digest = hashlib.sha256(bundle.read_bytes()).hexdigest()
    (bundle_root / "wooo__awoooi.bundle.sha256").write_text(
        f"{digest}  wooo__awoooi.bundle\n",
        encoding="utf-8",
    )

    result = subprocess.run(
        [
            "bash",
            str(SCRIPT),
            "--root",
            str(bundle_root),
            "--repo",
            "wooo/awoooi",
            "--write-textfile",
            "--textfile",
            str(textfile),
        ],
        text=True,
        capture_output=True,
        check=True,
    )

    assert "GITEA_BUNDLE_SAMPLE_RESTORE_DRY_RUN_OK=1" in result.stdout
    rendered = textfile.read_text(encoding="utf-8")
    assert 'awoooi_gitea_bundle_sample_restore_dry_run_ok{host="188",repo="wooo/awoooi"' in rendered
    assert 'bundle="wooo__awoooi.bundle",error=""} 1' in rendered
    assert "awoooi_gitea_bundle_sample_restore_dry_run_ref_count" in rendered
