#!/usr/bin/env python3
"""Read-only connectivity and CNI checks for the homelab mesh."""

from __future__ import annotations

import argparse
import json
import os
import shutil
import socket
import subprocess
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
from cluster_runtime_context import resolve


def run(command: list[str], timeout: int = 10) -> tuple[int, str, str]:
    try:
        completed = subprocess.run(command, text=True, capture_output=True, timeout=timeout)
    except (OSError, subprocess.TimeoutExpired) as exc:
        return 124, "", str(exc)
    return completed.returncode, completed.stdout.strip(), completed.stderr.strip()


def row(status: str, check: str, summary: str, detail: str = "") -> dict[str, str]:
    result = {"status": status, "check": check, "summary": summary}
    if detail:
        result["detail"] = detail
    return result


def tcp_check(name: str, host: str, port: int = 22) -> dict[str, str]:
    if not host:
        return row("warn", name, "not configured")
    try:
        with socket.create_connection((host, port), timeout=5):
            return row("pass", name, f"{host}:{port} reachable")
    except OSError as exc:
        return row("fail", name, f"{host}:{port} unreachable", str(exc))


def kubectl(kubeconfig: str, *args: str) -> tuple[int, str, str]:
    command = ["kubectl"]
    if kubeconfig:
        command += ["--kubeconfig", kubeconfig]
    return run(command + list(args), timeout=15)


def inventory(repo_root: Path) -> list[tuple[str, str, str]]:
    if resolve()["runtime"] == "k3s":
        return []
    path = repo_root / ".lab" / "pimox-workers.tsv"
    result = []
    if not path.is_file():
        return result
    for line in path.read_text().splitlines():
        fields = line.split("\t")
        if len(fields) >= 4 and fields[1] and fields[3]:
            result.append((fields[3], fields[1], fields[2] or ""))
    return result


def collect(repo_root: Path) -> dict:
    rows: list[dict[str, str]] = []
    cluster = resolve()
    kubeconfig = cluster["kubeconfig"]

    code, output, error = kubectl(kubeconfig, "get", "--raw=/readyz")
    if code == 0 and output:
        rows.append(row("pass", "Kubernetes API", "ready", output.replace("\n", "; ")))
    else:
        rows.append(row("fail", "Kubernetes API", "not ready", error or output or "kubectl failed"))

    code, output, error = kubectl(
        kubeconfig,
        "get",
        "nodes",
        "-o",
        "jsonpath={range .items[*]}{.metadata.name}{\"\\t\"}{.status.conditions[?(@.type==\"Ready\")].status}{\"\\n\"}{end}",
    )
    if code == 0:
        nodes = [line.split("\t", 1) for line in output.splitlines() if "\t" in line]
        unhealthy = [name for name, ready in nodes if ready != "True"]
        if unhealthy:
            rows.append(row("warn", "Kubernetes nodes", f"{len(nodes) - len(unhealthy)}/{len(nodes)} Ready", ", ".join(unhealthy)))
        else:
            rows.append(row("pass", "Kubernetes nodes", f"{len(nodes)}/{len(nodes)} Ready"))
    else:
        rows.append(row("warn", "Kubernetes nodes", "unable to inspect", error or output or "kubectl failed"))

    code, output, error = kubectl(kubeconfig, "-n", "calico-system", "get", "pods", "-l", "k8s-app=calico-node", "-o", "json")
    if code == 0:
        try:
            pods = json.loads(output).get("items", [])
            ready = 0
            for pod in pods:
                conditions = pod.get("status", {}).get("conditions", [])
                if any(c.get("type") == "Ready" and c.get("status") == "True" for c in conditions):
                    ready += 1
            status = "pass" if pods and ready == len(pods) else "warn"
            rows.append(row(status, "Calico node mesh", f"{ready}/{len(pods)} Ready"))
        except json.JSONDecodeError:
            rows.append(row("warn", "Calico node mesh", "invalid kubectl response"))
    else:
        rows.append(row("warn", "Calico node mesh", "unable to inspect", error or output or "kubectl failed"))

    control_plane = cluster["host"]
    rows.append(tcp_check("Control-plane SSH path", control_plane))
    for node, address, _user in inventory(repo_root):
        rows.append(tcp_check(f"{node} SSH path", address))

    tailscale = shutil.which("tailscale")
    if not tailscale:
        rows.append(row("warn", "Tailscale", "client not installed"))
    else:
        code, output, error = run([tailscale, "status", "--json"], timeout=10)
        if code != 0:
            rows.append(row("warn", "Tailscale", "status unavailable", error or output or "tailscale failed"))
        else:
            try:
                status = json.loads(output)
                backend = status.get("BackendState", "unknown")
                peers = len(status.get("Peer", {}) or {})
                rows.append(row("pass" if backend == "Running" else "warn", "Tailscale", f"{backend}; peers={peers}"))
            except json.JSONDecodeError:
                rows.append(row("warn", "Tailscale", "invalid status response"))
        targets = [item.strip() for item in os.environ.get("LAB_MESH_TAILSCALE_TARGETS", "").split(",") if item.strip()]
        for target in targets:
            code, output, error = run([tailscale, "ping", "--timeout=5s", target], timeout=8)
            if code == 0:
                path = "DERP relay" if "via DERP" in output else "direct path"
                rows.append(row("pass", f"Tailscale ping {target}", path, output.splitlines()[-1] if output else ""))
            else:
                rows.append(row("fail", f"Tailscale ping {target}", "unreachable", error or output or "tailscale ping failed"))

    counts = {state: sum(1 for item in rows if item["status"] == state) for state in ("pass", "warn", "fail")}
    overall = "fail" if counts["fail"] else "warn" if counts["warn"] else "pass"
    return {"title": "Mesh Doctor", "status": overall, "rows": rows, "counts": counts}


def main() -> int:
    parser = argparse.ArgumentParser(description="Read-only homelab mesh diagnostics")
    parser.add_argument("--json", action="store_true", dest="as_json")
    args = parser.parse_args()
    report = collect(Path(__file__).resolve().parents[1])
    if args.as_json:
        print(json.dumps(report, indent=2, sort_keys=False))
    else:
        print(f"== {report['title']} ==")
        for item in report["rows"]:
            print(f"{item['status']:<4} {item['check']:<24} {item['summary']}")
            if item.get("detail"):
                print(f"     detail: {item['detail']}")
        print(f"Overall: {report['status']} ({report['counts']})")
    return 1 if report["status"] == "fail" else 0


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