from __future__ import annotations

import json
import subprocess
import sys
from pathlib import Path


ROOT = Path(__file__).resolve().parents[3]
SCRIPT = ROOT / "scripts" / "security" / "gitea-authenticated-inventory-payload-validator.py"


def run_validator(path: Path | None = None, *, cwd: Path | None = None) -> dict:
    command = [sys.executable, str(SCRIPT)]
    if path:
        command.extend(["--input", str(path)])
    result = subprocess.run(
        command,
        cwd=cwd or ROOT / "apps/api",
        text=True,
        capture_output=True,
        check=True,
    )
    return json.loads(result.stdout)


def test_current_public_inventory_stays_needs_supplement() -> None:
    validation = run_validator()

    assert validation["schema_version"] == "gitea_authenticated_inventory_payload_validation_v1"
    assert validation["priority"] == "P0-003"
    assert validation["status"] == "needs_supplement"
    assert validation["result"]["accepted_payload_count"] == 0
    assert validation["result"]["token_value_collection_allowed"] is False
    assert validation["operation_boundaries"]["gitea_write_performed"] is False
    assert "visibility_scope_not_authenticated_or_admin_export" in validation["blockers"]
    assert "redaction_attestation_missing" in validation["blockers"]


def test_default_inventory_input_is_repo_root_relative_from_apps_api_cwd() -> None:
    validation = run_validator(cwd=ROOT / "apps" / "api")

    assert validation["status"] == "needs_supplement"
    assert validation["result"]["accepted_payload_count"] == 0


def test_accepts_redacted_admin_export_payload(tmp_path: Path) -> None:
    payload_path = tmp_path / "gitea-admin-export-redacted.json"
    payload_path.write_text(json.dumps(valid_payload()), encoding="utf-8")

    validation = run_validator(payload_path)

    assert validation["status"] == "accepted_for_private_inventory_review_only"
    assert validation["result"]["accepted_payload_count"] == 1
    assert validation["result"]["repo_count"] == 4
    assert validation["result"]["runtime_gate_count"] == 0
    assert validation["operation_boundaries"]["payload_persisted"] is False
    assert validation["operation_boundaries"]["repo_write_performed"] is False


def test_quarantines_secret_material(tmp_path: Path) -> None:
    payload = valid_payload()
    payload["repos"][0]["clone_url_redacted"] = "https://user:password@example.test/repo.git"
    payload_path = tmp_path / "secret-payload.json"
    payload_path.write_text(json.dumps(payload), encoding="utf-8")

    validation = run_validator(payload_path)

    assert validation["status"] == "quarantined_sensitive_payload"
    assert validation["result"]["accepted_payload_count"] == 0
    assert validation["result"]["sensitive_payload_hit_count"] >= 1


def test_rejects_execution_request(tmp_path: Path) -> None:
    payload = valid_payload()
    payload["repo_write_allowed"] = True
    payload_path = tmp_path / "execution-request.json"
    payload_path.write_text(json.dumps(payload), encoding="utf-8")

    validation = run_validator(payload_path)

    assert validation["status"] == "rejected_execution_request"
    assert validation["result"]["accepted_payload_count"] == 0
    assert validation["result"]["forbidden_true_field_count"] == 1
    assert validation["operation_boundaries"]["gitea_write_performed"] is False


def test_output_must_not_overwrite_input(tmp_path: Path) -> None:
    payload_path = tmp_path / "inventory.json"
    original = json.dumps(valid_payload())
    payload_path.write_text(original, encoding="utf-8")

    result = subprocess.run(
        [
            sys.executable,
            str(SCRIPT),
            "--input",
            str(payload_path),
            "--output",
            str(payload_path),
        ],
        text=True,
        capture_output=True,
        check=False,
    )

    assert result.returncode != 0
    assert "output_must_not_equal_input" in result.stderr
    assert payload_path.read_text(encoding="utf-8") == original


def valid_payload() -> dict:
    repos = [
        repo("wooo/awoooi"),
        repo("wooo/ewoooc"),
        repo("wooo/agent-bounty-protocol"),
        repo("wooo/2026FIFAWorldCup"),
    ]
    return {
        "schema_version": "gitea_repo_inventory_v1",
        "base_url": "https://gitea.wooo.work",
        "org": "wooo",
        "visibility_scope": "admin_export",
        "token_present": False,
        "status": "ok",
        "repo_count": len(repos),
        "repos": repos,
        "coverage_gap_explanation": {
            "public_only_vs_admin_export": "admin export includes all in-scope repos",
            "internal_110_adjacent_scope": "covered by owner scope decision",
            "org_user_endpoint_identity": "wooo namespace owner confirmed",
        },
        "redaction_attestation": {
            "no_token_value": True,
            "no_write_token": True,
            "no_webhook_secret": True,
            "no_deploy_key_private_key": True,
            "no_runner_registration_token": True,
            "no_cookie_or_session": True,
            "no_gitea_db_dump": True,
            "no_git_object_pack": True,
        },
    }


def repo(full_name: str) -> dict:
    _, name = full_name.split("/", 1)
    return {
        "gitea_repo": full_name,
        "name": name,
        "owner": "wooo",
        "private": False,
        "empty": False,
        "archived": False,
        "default_branch": "main",
        "clone_url_redacted": f"https://gitea.wooo.work/{full_name}.git",
        "ssh_url_redacted": f"ssh://gitea.wooo.work/{full_name}.git",
        "github_repo_candidate": "",
    }
