"""Hash-only MetaSolve API example. Does not upload repository source."""
import hashlib
import json
import os
import subprocess
import sys
import urllib.request


def git_value(*args: str) -> str:
    return subprocess.check_output(["git", *args], text=True).strip()


def main() -> int:
    api_key = os.environ.get("METASOLVE_API_KEY")
    if not api_key:
        raise SystemExit("METASOLVE_API_KEY is required")
    commit = git_value("rev-parse", "HEAD")
    repository = os.environ.get("CI_REPOSITORY", "unknown")
    source_digest = "sha256:" + hashlib.sha256((repository + ":" + commit).encode()).hexdigest()
    payload = {
        "client_reference": os.environ.get("CI_PIPELINE_ID", "custom-ci-" + commit[:12]),
        "prompt": "Verify bounded CI provenance and policy evidence for a governed release decision.",
        "answer": "Local security checks completed; source content remained in the customer pipeline.",
        "model": "ci-verification-artifact",
        "use_case": "ci_cd_release_gate",
        "repository": repository,
        "source_commit": commit,
        "proof_manifest_hash": source_digest,
        "policy_id": os.environ.get("METASOLVE_POLICY_ID", "ORG-SECURE-RELEASE"),
        "policy_version": os.environ.get("METASOLVE_POLICY_VERSION", "1.0"),
        "clause_id": os.environ.get("METASOLVE_CLAUSE_ID", "APPSEC-GATE"),
        "policy_approval_status": os.environ.get("METASOLVE_POLICY_APPROVAL_STATUS", "Approved"),
        "environment": os.environ.get("DEPLOY_ENVIRONMENT", "staging"),
        "metadata": {"metasolve_ci_schema": "metasolve.ci_verification.v1", "raw_source_uploaded": "false"},
    }
    request = urllib.request.Request(
        os.environ.get("METASOLVE_BASE_URL", "https://app.metasolve.ca").rstrip("/") + "/api/v1/trust/verify",
        data=json.dumps(payload).encode(), method="POST",
        headers={"Authorization": "Bearer " + api_key, "Content-Type": "application/json", "Accept": "application/json"},
    )
    with urllib.request.urlopen(request, timeout=30) as response:
        result = json.load(response)
    decision = str((result.get("release_gate") or {}).get("decision", "blocked")).lower()
    print(json.dumps({"decision": decision, "verification": result.get("verification")}, sort_keys=True))
    return 0 if decision == "passed" else 3


if __name__ == "__main__":
    sys.exit(main())
