#!/usr/bin/env python3
from __future__ import annotations

import argparse
import json
import re
import sys
from pathlib import Path

sys.path.insert(0, str((Path(__file__).resolve().parent / "lib")))
from state_paths import (  # noqa: E402
    BUILDER_HOST_STATE_FILE,
    BUILDER_RESCUE_FACTS_FILE,
    BUILDER_ROOTFS_PLAN_FILE,
    BUILDER_REMOTE_CONF_FILE,
    LEGACY_STATE_FILES,
    load_json_file,
)


def parse_builder_spec(conf: Path) -> dict[str, str]:
    text = conf.read_text() if conf.exists() else ""
    match = re.search(r"^builders = (?P<spec>.+)$", text, re.M)
    if not match:
        return {}
    spec = match.group("spec")
    host_match = re.search(r"://[^@]+@(?P<host>\[[^\]]+\]|[^ ]+) ", spec)
    key_match = re.search(r" - (?P<hostkey>[A-Za-z0-9+/=]+)$", spec)
    return {
        "spec": spec,
        "host": host_match.group("host") if host_match else "",
        "host_key_base64": key_match.group("hostkey") if key_match else "",
    }


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--json", action="store_true")
    args = parser.parse_args()

    host_state = load_json_file(BUILDER_HOST_STATE_FILE)
    rescue_facts = load_json_file(BUILDER_RESCUE_FACTS_FILE)
    rootfs_plan = load_json_file(BUILDER_ROOTFS_PLAN_FILE)
    remote_conf = parse_builder_spec(BUILDER_REMOTE_CONF_FILE)

    issues: list[str] = []
    warnings: list[str] = []

    if not BUILDER_HOST_STATE_FILE.exists():
        issues.append(f"Missing state file: {BUILDER_HOST_STATE_FILE}")
    else:
        if not (host_state.get("server_host") or host_state.get("server_ip")):
            issues.append("builder-host.json is missing server_host/server_ip")
        if host_state.get("builder_registered_features") and not host_state.get("builder_supported_features"):
            warnings.append("builder_registered_features set without builder_supported_features")
        supported = set(str(host_state.get("builder_supported_features", "")).split(",")) - {""}
        registered_value = host_state.get("builder_registered_features") or ""
        registered = set(str(registered_value).split(",")) - {""}
        if supported and registered and not registered.issubset(supported):
            issues.append(
                "Registered builder features are not a subset of supported features: "
                f"registered={sorted(registered)} supported={sorted(supported)}"
            )

    if BUILDER_RESCUE_FACTS_FILE.exists() != BUILDER_ROOTFS_PLAN_FILE.exists():
        issues.append("Rescue facts and rootfs plan should either both exist or both be absent")

    if BUILDER_REMOTE_CONF_FILE.exists():
        if not remote_conf.get("spec"):
            issues.append(f"Missing builders entry in {BUILDER_REMOTE_CONF_FILE}")
        state_host = host_state.get("server_host") or host_state.get("server_ip") or ""
        conf_host = remote_conf.get("host", "").strip("[]")
        if state_host and conf_host and state_host != conf_host:
            issues.append(f"builder-remote.conf host {conf_host} does not match state host {state_host}")
        state_host_key = host_state.get("builder_host_key_base64") or ""
        conf_host_key = remote_conf.get("host_key_base64") or ""
        if state_host_key and conf_host_key and state_host_key != conf_host_key:
            issues.append("builder-remote.conf host key does not match builder-host.json")

    for legacy_name, legacy_path in LEGACY_STATE_FILES.items():
        if legacy_path.exists():
            issues.append(f"Legacy state file still present: {legacy_name} -> {legacy_path}")

    report = {
        "state_files": {
            "builder_host": str(BUILDER_HOST_STATE_FILE),
            "builder_rescue_facts": str(BUILDER_RESCUE_FACTS_FILE),
            "builder_rootfs_plan": str(BUILDER_ROOTFS_PLAN_FILE),
            "builder_remote_conf": str(BUILDER_REMOTE_CONF_FILE),
        },
        "state_summary": {
            "server_host": host_state.get("server_host") or host_state.get("server_ip"),
            "server_number": host_state.get("server_number"),
            "builder_supported_features": host_state.get("builder_supported_features"),
            "builder_registered_features": host_state.get("builder_registered_features"),
            "has_rescue_facts": BUILDER_RESCUE_FACTS_FILE.exists(),
            "has_rootfs_plan": BUILDER_ROOTFS_PLAN_FILE.exists(),
            "has_remote_conf": BUILDER_REMOTE_CONF_FILE.exists(),
            "layout": rootfs_plan.get("layout"),
        },
        "warnings": warnings,
        "issues": issues,
        "ok": not issues,
    }

    if args.json:
        print(json.dumps(report, indent=2))
    else:
        print(json.dumps(report, indent=2))

    if issues:
        raise SystemExit(1)


if __name__ == "__main__":
    main()
