#!/usr/bin/env python3
"""Regression tests for target-host HTTP status classification."""
from __future__ import annotations

import importlib.util
import json
import sys
sys.dont_write_bytecode = True
from pathlib import Path
from unittest.mock import patch

ROOT = Path(__file__).resolve().parents[2]
TOOL = ROOT / "tools" / "target_host_acceptance_22072026163824.py"
spec = importlib.util.spec_from_file_location("target_host_acceptance", TOOL)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
sys.modules[spec.name] = module
spec.loader.exec_module(module)


def run_case(api_status: int, api_payload: dict) -> list:
    def fake_request(url: str, timeout: float, method: str = "GET"):
        if url.endswith("/api/status"):
            return api_status, {"content-type": "application/json", "cache-control": "no-store"}, json.dumps(api_payload).encode()
        blocked = ("server/config.php", "server/bootstrap.php", "storage/", ".htaccess", "DEPLOYMENT_MANIFEST.json", "sbom.cdx.json", "CHANGES_000000000000.txt")
        if any(url.endswith("/" + item) for item in blocked):
            return 403, {"content-type": "text/plain"}, b"Forbidden"
        content_type = "application/manifest+json" if url.endswith("manifest.webmanifest") else "application/javascript" if url.endswith("sw.js") else "text/html"
        return 200, {"content-type": content_type}, b"ok"

    checks = []
    with patch.object(module, "request", fake_request):
        module.http_checks("https://example.test/app/", 1.0, checks)
    return checks


healthy = run_case(200, {"ok": True, "data": {"state": "setup_required", "runtime": {}}})
healthy_status = next(check for check in healthy if check.name == "http:api-status")
assert healthy_status.status == "Passed", healthy_status

preflight = run_case(503, {"ok": False, "error": {"code": "ENVIRONMENT_INVALID", "failures": ["Missing PHP extension: sqlite3."]}})
preflight_status = next(check for check in preflight if check.name == "http:api-status")
assert preflight_status.status == "Passed", preflight_status

invalid = run_case(503, {"ok": False, "error": {"code": "INTERNAL_ERROR", "failures": []}})
invalid_status = next(check for check in invalid if check.name == "http:api-status")
assert invalid_status.status == "Failed", invalid_status

print("Target-host acceptance status regression tests passed.")
