"""Register validation-control tests without weakening existing policies."""

from __future__ import annotations

import argparse
import hashlib
import json
import os
import pathlib
import sys


ROOT = pathlib.Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "src"))

from reliability_core.suite_isolation import (  # noqa: E402
    discover_test_ids,
    load_policy_manifest,
    validate_policy_manifest,
)


PREFIX = "tests.test_validation_control.ValidationControlTests."


def sha256_file(path: pathlib.Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest()


def entry(test_id: str) -> dict[str, object]:
    return {
        "creates_process": False,
        "creates_thread": False,
        "mutates_environment": False,
        "policy": "SAFE_SHARED_WORKER",
        "reason": "isolated temporary-directory checkpoint contract with no process, signal, global cache, or environment mutation",
        "required_cleanup_assertions": [
            "worker_exit_code",
            "failure_count",
            "error_count",
        ],
        "requirement_ids": ["VALIDATION_CONTROL"],
        "test_id": test_id,
        "timeout_profile": "shared_safe",
        "uses_global_cache": False,
        "uses_signal": False,
    }


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--apply", action="store_true")
    args = parser.parse_args()
    path = ROOT / "test_execution_manifest.json"
    payload = load_policy_manifest(path)
    before = sha256_file(path)
    discovered = discover_test_ids(ROOT)
    current = {str(row["test_id"]): row for row in payload["tests"]}
    missing = sorted(set(discovered) - set(current))
    unknown = sorted(set(current) - set(discovered))
    if unknown:
        raise SystemExit(json.dumps({"unknown_manifest_test_ids": unknown}, sort_keys=True))
    forbidden = [test_id for test_id in missing if not test_id.startswith(PREFIX)]
    if forbidden:
        raise SystemExit(json.dumps({"unclassified_new_test_ids": forbidden}, sort_keys=True))
    updated = {**current, **{test_id: entry(test_id) for test_id in missing}}
    output = {
        **payload,
        "discovered_test_count": len(discovered),
        "generated_from_discovery": True,
        "tests": [updated[test_id] for test_id in sorted(updated)],
    }
    rendered = json.dumps(output, ensure_ascii=False, indent=2, sort_keys=True) + "\n"
    after = hashlib.sha256(rendered.encode("utf-8")).hexdigest()
    if args.apply:
        temporary = path.with_suffix(path.suffix + ".validation-control.tmp")
        temporary.write_text(rendered, encoding="utf-8", newline="\n")
        os.replace(temporary, path)
        after = sha256_file(path)
    validation = validate_policy_manifest(output, discovered)
    result = {
        "applied": args.apply,
        "before_sha256": before,
        "after_sha256": after,
        "added_count": len(missing),
        "discovered_count": len(discovered),
        "validation": validation,
    }
    print(json.dumps(result, ensure_ascii=False, sort_keys=True))
    return 0 if validation["passed"] else 1


if __name__ == "__main__":
    raise SystemExit(main())
