#!/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
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Any

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 = {
    "JeannieApiMetricsDown",
    "HomelabNodeDiskPressure",
    "HomelabNodeImageFilesystemPressure",
    "HomelabStaleResidualPods",
    "FreeDiskSpaceFailed",
    "KubePodContainerStatusUnknown",
    "KubePodEvicted",
}

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


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 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) -> subprocess.CompletedProcess[str]:
    process = subprocess.run(
        command,
        cwd=REPO_ROOT,
        text=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        check=False,
    )
    write_text(audit_dir / f"{name}.cmd", " ".join(command) + "\n")
    write_text(audit_dir / f"{name}.log", process.stdout)
    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]:
    key = event_key(payload)
    audit_dir = EVENT_DIR / f"{utc_stamp()}-{key}"
    audit_dir.mkdir(parents=True, exist_ok=True)
    (audit_dir / "alertmanager.json").write_text(
        json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8"
    )

    names = sorted(alert_names(payload))
    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

    api_command = api_self_heal_command(set(names))
    if api_command:
        result = {
            "status": "planned",
            "mode": "dry-run",
            "alerts": names,
            "audit_dir": str(audit_dir),
            "planned_command": " ".join(api_command),
        }
        if apply:
            apply_result = run_command(api_command, audit_dir, "api-heal")
            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")
    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",
    )
    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",
        )
        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]]] = []
    if not EVENT_DIR.is_dir():
        return documents
    for path in sorted(EVENT_DIR.glob("*/result.json")):
        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())
