"""Fail closed if Core deploy wiring or sibling Cloud configs can hit production."""

from __future__ import annotations

import re
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
CLOUD = ROOT.parent / "P2HSCloud"
DASH = ROOT.parent / "P2HS-Dash"
PRODUCTION_D1 = "f01a2da8-12b3-494d-85f0-e5c9bf263acb"
PRODUCTION_CORE = "beapipie.p2hs.com"
PLACEHOLDER_D1 = "00000000-0000-4000-a000-000000000001"


def deploy_workflow() -> str:
    return (ROOT / ".github/workflows/deploy.yml").read_text(encoding="utf-8")


def production_deploy_is_main_only(text: str | None = None) -> bool:
    source = text if text is not None else deploy_workflow()
    block = source.split("deploy_main:", 1)[-1].split("deploy_staging:", 1)[0]
    return "if: github.ref == 'refs/heads/main'" in block


def phase13_is_not_an_auto_deploy_branch(text: str | None = None) -> bool:
    source = text if text is not None else deploy_workflow()
    header = source.split("jobs:", 1)[0]
    push = header.split("pull_request:", 1)[0]
    listed = [
        line.strip().lstrip("-").strip()
        for line in push.splitlines()
        if line.strip().startswith("- ")
    ]
    return "codex/phase13-reliability" not in listed


def cloud_wrangler_texts() -> list[tuple[str, str]]:
    if not CLOUD.is_dir():
        return []
    rows = []
    for path in sorted(CLOUD.glob("apps/*/wrangler.toml")):
        rel = str(path.relative_to(CLOUD)).replace("\\", "/")
        rows.append((rel, path.read_text(encoding="utf-8")))
    return rows


def cloud_isolated_from_production() -> bool:
    rows = cloud_wrangler_texts()
    if not rows:
        return False
    for _rel, text in rows:
        if PRODUCTION_D1 in text:
            return False
        if PRODUCTION_CORE in text:
            return False
        match = re.search(r'^name = "([^"]+)"', text, re.M)
        if match and not match.group(1).endswith("-staging"):
            return False
    return True


def cloud_resources_provisioned() -> bool:
    rows = cloud_wrangler_texts()
    if not rows:
        return False
    return all(PLACEHOLDER_D1 not in text for _rel, text in rows)


def dash_worker_is_scoped() -> bool:
    path = DASH / "wrangler.jsonc"
    if not path.is_file():
        return False
    text = path.read_text(encoding="utf-8")
    return '"name": "p2hsdash-staging"' in text and '"name": "p2hsdash"' not in text.replace(
        '"name": "p2hsdash-staging"', ""
    )


def inspect() -> dict:
    deploy = deploy_workflow()
    return {
        "production_deploy_is_main_only": production_deploy_is_main_only(deploy),
        "phase13_not_in_deploy_on_push": phase13_is_not_an_auto_deploy_branch(deploy),
        "cloud_isolated_from_production": cloud_isolated_from_production(),
        "cloud_resources_provisioned": cloud_resources_provisioned(),
        "dash_worker_is_scoped": dash_worker_is_scoped(),
        "local_alembic_head_expected": "145",
    }


def main() -> int:
    result = inspect()
    blockers = [
        key
        for key in (
            "production_deploy_is_main_only",
            "phase13_not_in_deploy_on_push",
            "cloud_isolated_from_production",
            "dash_worker_is_scoped",
        )
        if not result[key]
    ]
    print(result)
    if blockers:
        print("13S isolation blockers:", blockers)
        return 1
    if not result["cloud_resources_provisioned"]:
        print("13S isolated from production, but staging Cloud resources are not provisioned.")
        return 2
    return 0


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