#!/usr/bin/env python3
"""Headless Alertmanager webhook runner for Jeannie-native self-healing."""

from __future__ import annotations

import argparse
import datetime as dt
import hashlib
import json
import os
import re
import subprocess
import sys
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Any
sys.path.insert(0, str(Path(__file__).resolve().parent))
from cluster_runtime_context import resolve, environment

REPO_ROOT = Path(__file__).resolve().parents[1]
STATE_DIR = Path(
    os.environ.get(
        "HOMELAB_STATE_DIR",
        Path(os.environ.get("XDG_DATA_HOME", Path.home() / ".local/share")) / "homelab",
    )
)
EVENT_DIR = Path(os.environ.get("LAB_SELF_HEAL_EVENT_DIR", STATE_DIR / "self-heal-events"))
DEFAULT_DOCTOR = ["./jeannie", "doctor-homelab", "--json", "--no-local-rca"]

SUPPORTED_ALERTS = {
    "KubeNodeNotReady",
    "KubeAPIDown",
    "KubeletDown",
    "JeannieApiMetricsDown",
    "HomelabNodeDiskPressure",
    "HomelabNodeImageFilesystemPressure",
    "HomelabHostFilesystemNearlyFull",
    "HomelabStaleResidualPods",
    "FreeDiskSpaceFailed",
    "KubePodContainerStatusUnknown",
    "KubePodEvicted",
}

API_SELF_HEAL_COMMANDS = {
    "JeannieApiMetricsDown": ["sudo", "systemctl", "restart", "jeannie-server.service"],
}

DISK_SELF_HEAL_ALERTS = {
    "HomelabNodeDiskPressure",
    "HomelabNodeImageFilesystemPressure",
    "HomelabHostFilesystemNearlyFull",
    "FreeDiskSpaceFailed",
}

STALE_POD_SELF_HEAL_ALERTS = {
    "HomelabStaleResidualPods",
    "KubePodContainerStatusUnknown",
    "KubePodEvicted",
}

# Debian is intentionally monitored but excluded from automatic disk cleanup:
# its constrained root/data layout has no safe generic deletion target.  Keep
# this list explicit so adding another host cannot accidentally enable cleanup.
DISK_SELF_HEAL_DISABLED_HOSTS = {
    item.strip().lower()
    for item in os.environ.get(
        "LAB_DISK_SELF_HEAL_DISABLED_HOSTS", "debian,debian-lab,debian-2"
    ).split(",")
    if item.strip()
}


def prom_escape(value: object) -> str:
    text = str(value)
    return text.replace("\\", "\\\\").replace("\n", "\\n").replace('"', '\\"')


def action_name(command: str) -> str:
    if "cleanup-stale-pods" in command:
        return "cleanup_stale_pods"
    if not command:
        return "none"
    return re.sub(r"[^a-zA-Z0-9_]+", "_", command.strip()).strip("_")[:80] or "unknown"


def utc_stamp() -> str:
    return dt.datetime.now(dt.UTC).strftime("%Y%m%dT%H%M%SZ")


def event_key(payload: dict[str, Any]) -> str:
    alerts = payload.get("alerts") or []
    if alerts and isinstance(alerts, list):
        fingerprint = str(alerts[0].get("fingerprint") or "")
        if fingerprint:
            return fingerprint
        labels = alerts[0].get("labels") or {}
        if isinstance(labels, dict):
            label_blob = json.dumps(labels, sort_keys=True)
            return hashlib.sha256(label_blob.encode()).hexdigest()[:16]
    return hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest()[:16]


def alert_names(payload: dict[str, Any]) -> set[str]:
    names: set[str] = set()
    for alert in payload.get("alerts") or []:
        if not isinstance(alert, dict):
            continue
        labels = alert.get("labels") or {}
        annotations = alert.get("annotations") or {}
        for value in (
            labels.get("alertname"),
            labels.get("reason"),
            annotations.get("reason"),
        ):
            if value:
                names.add(str(value))
        blob = json.dumps(alert, sort_keys=True)
        if "FreeDiskSpaceFailed" in blob:
            names.add("FreeDiskSpaceFailed")
    return names


def supported(payload: dict[str, Any]) -> bool:
    return bool(alert_names(payload) & SUPPORTED_ALERTS)


def api_self_heal_command(names: set[str]) -> list[str] | None:
    for name, command in API_SELF_HEAL_COMMANDS.items():
        if name in names:
            return command
    return None


def disk_self_heal_command(payload: dict[str, Any], names: set[str], cluster=None) -> list[str] | None:
    if not names & DISK_SELF_HEAL_ALERTS:
        return None
    labels_list: list[dict[str, Any]] = []
    for alert in payload.get("alerts") or []:
        if isinstance(alert, dict) and isinstance(alert.get("labels"), dict):
            labels_list.append(alert["labels"])
    common_labels = payload.get("commonLabels")
    if isinstance(common_labels, dict):
        labels_list.append(common_labels)

    cluster = cluster or resolve(follow_active=True)
    for labels in labels_list:
        host_values = (
            labels.get("node"),
            labels.get("hostname"),
            labels.get("host"),
            labels.get("instance"),
        )
        normalized_hosts = {
            str(value).split(":", 1)[0].lower()
            for value in host_values
            if value
        }
        if normalized_hosts & DISK_SELF_HEAL_DISABLED_HOSTS:
            return None
        node = str(labels.get("node") or "")
        if cluster["runtime"] == "k3s":
            if node == cluster["node"] or normalized_hosts & {cluster["node"], cluster["host"]}:
                return ["./jeannie", "workers", "disk-cleanup", "control-plane", "--yes"]
            continue
        if re.fullmatch(r"pimox-cp(?:-\d+)?", node):
            return ["./jeannie", "workers", "disk-cleanup", "control-plane", "--yes"]
        match = re.fullmatch(r"pimox-worker-(\d{1,2})", node)
        if match:
            return ["./jeannie", "workers", "disk-cleanup", str(int(match.group(1))), "--yes"]

    if cluster["runtime"] == "k3s":
        return None
    spec_file = REPO_ROOT / ".lab" / "pimox-workers.tsv"
    if spec_file.is_file():
        for labels in labels_list:
            instance = str(labels.get("instance") or "").split(":", 1)[0]
            if not instance:
                continue
            try:
                rows = spec_file.read_text(encoding="utf-8").splitlines()
            except OSError:
                break
            for row in rows:
                fields = row.split("\t")
                if len(fields) < 4 or fields[1] != instance:
                    continue
                node = fields[3]
                if re.fullmatch(r"pimox-cp(?:-\d+)?", node):
                    return ["./jeannie", "workers", "disk-cleanup", "control-plane", "--yes"]
                match = re.fullmatch(r"pimox-worker-(\d{1,2})", node)
                if match:
                    return ["./jeannie", "workers", "disk-cleanup", str(int(match.group(1))), "--yes"]
    return None


def write_text(path: Path, text: str) -> None:
    path.write_text(text, encoding="utf-8")


def run_command(command: list[str], audit_dir: Path, name: str, env=None) -> subprocess.CompletedProcess[str]:
    env = env or environment(resolve(follow_active=True)["profile"])
    if name in {"disk-heal", "api-heal", "pod-heal", "heal-apply"}:
        guard_command = [sys.executable, str(REPO_ROOT / "scripts/cluster-context.py"), "check-startup" if name == "heal-apply" else "check"]
        guard_command.extend(["--profile", env["LAB_CLUSTER_PROFILE"]])
        kubeconfig = env["KUBECONFIG"]
        if kubeconfig:
            guard_command.extend(["--kubeconfig", kubeconfig])
        guard = subprocess.run(
            guard_command,
            cwd=REPO_ROOT, text=True, capture_output=True, check=False, env=env,
        )
        if guard.returncode:
            write_text(audit_dir / f"{name}.stderr.log", guard.stderr)
            write_text(audit_dir / f"{name}.cmd", " ".join(command) + "\n")
            write_text(audit_dir / f"{name}.status", str(guard.returncode) + "\n")
            return subprocess.CompletedProcess(command, guard.returncode, "", guard.stderr)
        write_text(audit_dir / f"{name}.identity.json", guard.stdout)
    process = subprocess.run(
        command,
        cwd=REPO_ROOT,
        text=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        check=False,
        env=env,
    )
    write_text(audit_dir / f"{name}.cmd", " ".join(command) + "\n")
    write_text(audit_dir / f"{name}.log", process.stdout)
    # Doctor stdout is parsed as JSON by scripts/heal. Startup diagnostics
    # (including OCI config notices) must not be merged into that document.
    write_text(audit_dir / f"{name}.stderr.log", process.stderr)
    write_text(audit_dir / f"{name}.status", f"{process.returncode}\n")
    return process


def planned_command(plan_output: str) -> str:
    for line in plan_output.splitlines():
        line = line.strip()
        if line.startswith("command:"):
            return line.removeprefix("command:").strip()
    return ""


def handle_payload(payload: dict[str, Any], *, apply: bool) -> dict[str, Any]:
    cluster = resolve(follow_active=True)
    event_env = environment(cluster["profile"])
    key = event_key(payload)
    event_dir = Path(os.environ.get("LAB_SELF_HEAL_EVENT_DIR", Path(cluster["root"]) / "self-heal-events"))
    audit_dir = event_dir / f"{utc_stamp()}-{key}"
    audit_dir.mkdir(parents=True, exist_ok=True)
    write_text(audit_dir / "cluster.json", json.dumps({key: cluster[key] for key in ("profile", "runtime", "host", "node", "kubeconfig", "uid")}, indent=2) + "\n")
    (audit_dir / "alertmanager.json").write_text(
        json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8"
    )

    names = sorted(alert_names(payload))
    labelled_profiles = {str(alert.get("labels", {}).get("cluster_profile"))
                         for alert in payload.get("alerts") or [] if alert.get("labels", {}).get("cluster_profile")}
    labelled_uids = {str(alert.get("labels", {}).get("cluster_uid"))
                     for alert in payload.get("alerts") or [] if alert.get("labels", {}).get("cluster_uid")}
    incomplete_identity = any(
        alert.get("labels", {}).get("cluster_profile") != cluster["profile"]
        or alert.get("labels", {}).get("cluster_uid") != cluster["uid"]
        for alert in payload.get("alerts") or []
    )
    if ((labelled_profiles and labelled_profiles != {cluster["profile"]})
            or (labelled_uids and labelled_uids != {cluster["uid"]})
            or (apply and (incomplete_identity or labelled_profiles != {cluster["profile"]} or not cluster["uid"] or labelled_uids != {cluster["uid"]}))):
        result = {"status": "skipped", "reason": "alert cluster identity is absent or differs from the selected cluster; deploy monitoring labels before automatic healing", "audit_dir": str(audit_dir)}
        write_text(audit_dir / "result.json", json.dumps(result) + "\n")
        return result
    if not supported(payload):
        result = {
            "status": "skipped",
            "reason": "alert is not in first-phase self-heal allowlist",
            "alerts": names,
            "audit_dir": str(audit_dir),
        }
        write_text(audit_dir / "result.json", json.dumps(result, indent=2) + "\n")
        return result

    disk_command = disk_self_heal_command(payload, set(names), cluster=cluster)
    api_command = api_self_heal_command(set(names))
    # An eviction cleanup alert must not select an unrelated host restart from
    # the broad doctor report. Cleanup performs its own ownership/state checks.
    pod_command = (
        ["./jeannie", "heal", "cleanup-stale-pods", "--yes"]
        if set(names) & STALE_POD_SELF_HEAL_ALERTS else None
    )
    direct_command = disk_command or api_command or pod_command
    # Disk alerts are deliberately target-specific.  Do not fall through to
    # the generic doctor/heal planner when the alert does not identify a
    # selected cluster node that Jeannie can clean safely. A generic heal action could
    # clean stale pods while leaving the actual filesystem pressure untouched
    # and would produce a misleading "applied" result.
    if set(names) & DISK_SELF_HEAL_ALERTS and not disk_command and not api_command:
        result = {
            "status": "skipped",
            "reason": "disk alert target is not a recognized node in the selected cluster profile",
            "alerts": names,
            "audit_dir": str(audit_dir),
        }
        write_text(audit_dir / "result.json", json.dumps(result, indent=2, sort_keys=True) + "\n")
        return result
    if direct_command:
        result = {
            "status": "planned",
            "mode": "dry-run",
            "alerts": names,
            "audit_dir": str(audit_dir),
            "planned_command": " ".join(direct_command),
        }
        if apply:
            apply_result = run_command(
                direct_command,
                audit_dir,
                "disk-heal" if disk_command else "api-heal" if api_command else "pod-heal",
                env=event_env,
            )
            result["status"] = "applied" if apply_result.returncode == 0 else "apply_failed"
            result["mode"] = "apply"
            result["apply_status"] = apply_result.returncode
        write_text(audit_dir / "result.json", json.dumps(result, indent=2, sort_keys=True) + "\n")
        return result

    doctor = run_command(DEFAULT_DOCTOR, audit_dir, "doctor-homelab", env=event_env)
    if doctor.returncode != 0 and not doctor.stdout.strip():
        result = {
            "status": "failed",
            "reason": "doctor-homelab produced no JSON",
            "alerts": names,
            "audit_dir": str(audit_dir),
        }
        write_text(audit_dir / "result.json", json.dumps(result, indent=2) + "\n")
        return result

    status_json = audit_dir / "doctor-homelab.log"
    plan = run_command(
        ["./scripts/heal", "plan", "--status-json", str(status_json)],
        audit_dir,
        "heal-plan",
        env=event_env,
    )
    result: dict[str, Any] = {
        "status": "planned",
        "mode": "dry-run",
        "alerts": names,
        "audit_dir": str(audit_dir),
        "doctor_status": doctor.returncode,
        "plan_status": plan.returncode,
        "planned_command": planned_command(plan.stdout),
    }
    if apply:
        apply_result = run_command(
            ["./scripts/heal", "apply", "--status-json", str(status_json), "--yes"],
            audit_dir,
            "heal-apply",
            env=event_env,
        )
        result["status"] = "applied" if apply_result.returncode == 0 else "apply_failed"
        result["mode"] = "apply"
        result["apply_status"] = apply_result.returncode

    write_text(audit_dir / "result.json", json.dumps(result, indent=2, sort_keys=True) + "\n")
    return result


def result_documents() -> list[tuple[Path, dict[str, Any]]]:
    documents: list[tuple[Path, dict[str, Any]]] = []
    paths = set(EVENT_DIR.glob("*/result.json"))
    paths.update((STATE_DIR / "clusters").glob("*/self-heal-events/*/result.json"))
    for path in sorted(paths):
        try:
            document = json.loads(path.read_text(encoding="utf-8"))
        except (OSError, json.JSONDecodeError):
            continue
        if isinstance(document, dict):
            documents.append((path, document))
    return documents


def unix_timestamp_from_audit_dir(path: Path) -> int:
    stamp = path.parent.name.split("-", 1)[0]
    try:
        parsed = dt.datetime.strptime(stamp, "%Y%m%dT%H%M%SZ").replace(tzinfo=dt.UTC)
    except ValueError:
        return 0
    return int(parsed.timestamp())


def metrics_text() -> str:
    documents = result_documents()
    event_counts: dict[tuple[str, str], int] = {}
    alert_counts: dict[tuple[str, str], int] = {}
    action_counts: dict[tuple[str, str], int] = {}
    last_timestamp = 0
    last_status = "none"
    last_action = "none"

    for path, document in documents:
        status = str(document.get("status") or "unknown")
        mode = str(document.get("mode") or "unknown")
        command = str(document.get("planned_command") or "")
        action = action_name(command)
        timestamp = unix_timestamp_from_audit_dir(path)
        event_counts[(status, mode)] = event_counts.get((status, mode), 0) + 1
        for alert in document.get("alerts") or ["unknown"]:
            alert_counts[(str(alert), status)] = alert_counts.get((str(alert), status), 0) + 1
        if mode == "apply":
            action_counts[(action, status)] = action_counts.get((action, status), 0) + 1
        if timestamp >= last_timestamp:
            last_timestamp = timestamp
            last_status = status
            last_action = action

    lines = [
        "# HELP jeannie_self_heal_info Jeannie self-heal webhook static info.",
        "# TYPE jeannie_self_heal_info gauge",
        'jeannie_self_heal_info{service="jeannie-eventd"} 1',
        "# HELP jeannie_self_heal_events_total Count of Jeannie self-heal webhook events by result status and mode.",
        "# TYPE jeannie_self_heal_events_total counter",
    ]
    for (status, mode), count in sorted(event_counts.items()):
        lines.append(
            f'jeannie_self_heal_events_total{{status="{prom_escape(status)}",mode="{prom_escape(mode)}"}} {count}'
        )
    lines.extend(
        [
            "# HELP jeannie_self_heal_alerts_total Count of alert names processed by Jeannie self-heal.",
            "# TYPE jeannie_self_heal_alerts_total counter",
        ]
    )
    for (alert, status), count in sorted(alert_counts.items()):
        lines.append(
            f'jeannie_self_heal_alerts_total{{alertname="{prom_escape(alert)}",status="{prom_escape(status)}"}} {count}'
        )
    lines.extend(
        [
            "# HELP jeannie_self_heal_actions_total Count of apply-mode Jeannie self-heal actions by action and result.",
            "# TYPE jeannie_self_heal_actions_total counter",
        ]
    )
    for (action, status), count in sorted(action_counts.items()):
        lines.append(
            f'jeannie_self_heal_actions_total{{action="{prom_escape(action)}",status="{prom_escape(status)}"}} {count}'
        )
    lines.extend(
        [
            "# HELP jeannie_self_heal_last_event_timestamp_seconds Unix timestamp for latest Jeannie self-heal event.",
            "# TYPE jeannie_self_heal_last_event_timestamp_seconds gauge",
            f'jeannie_self_heal_last_event_timestamp_seconds{{status="{prom_escape(last_status)}",action="{prom_escape(last_action)}"}} {last_timestamp}',
            "",
        ]
    )
    return "\n".join(lines)


def load_payload(path: str) -> dict[str, Any]:
    if path == "-":
        return json.loads(os.sys.stdin.read())
    return json.loads(Path(path).read_text(encoding="utf-8"))


class Handler(BaseHTTPRequestHandler):
    apply = False

    def do_GET(self) -> None:  # noqa: N802
        if self.path != "/metrics":
            self.send_error(404)
            return
        body = metrics_text().encode()
        self.send_response(200)
        self.send_header("content-type", "text/plain; version=0.0.4; charset=utf-8")
        self.send_header("content-length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def do_POST(self) -> None:  # noqa: N802
        length = int(self.headers.get("content-length", "0"))
        payload = json.loads(self.rfile.read(length))
        result = handle_payload(payload, apply=self.apply)
        body = json.dumps(result, indent=2, sort_keys=True).encode()
        self.send_response(200)
        self.send_header("content-type", "application/json")
        self.send_header("content-length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def log_message(self, format: str, *args: object) -> None:
        print(f"jeannie-eventd: {format % args}")


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    subparsers = parser.add_subparsers(dest="command", required=True)
    dry_run = subparsers.add_parser("dry-run")
    dry_run.add_argument("alert_json")
    dry_run.add_argument("--apply", action="store_true")
    serve = subparsers.add_parser("serve")
    serve.add_argument("--host", default=os.environ.get("LAB_SELF_HEAL_HOST", "127.0.0.1"))
    serve.add_argument("--port", type=int, default=int(os.environ.get("LAB_SELF_HEAL_PORT", "18081")))
    serve.add_argument("--apply", action="store_true")
    args = parser.parse_args()

    if args.command == "dry-run":
        result = handle_payload(load_payload(args.alert_json), apply=args.apply)
        print(json.dumps(result, indent=2, sort_keys=True))
        return 0

    if args.command == "serve":
        Handler.apply = bool(args.apply or os.environ.get("LAB_SELF_HEAL_APPLY") == "true")
        server = ThreadingHTTPServer((args.host, args.port), Handler)
        print(f"jeannie-eventd listening on http://{args.host}:{args.port} apply={Handler.apply}")
        server.serve_forever()
    return 2


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