#!/usr/bin/env python3
"""Generate Homepage dashboard config from homelab inventory and Heimdall links."""

from __future__ import annotations

import argparse
import json
import pathlib
import re
from typing import Any

REPO_ROOT = pathlib.Path(__file__).resolve().parents[1]
INVENTORY = REPO_ROOT / "homelab.yml"
HEIMDALL_LINKS = REPO_ROOT / "infra" / "heimdall" / "links.json"
OUTPUT_DIR = REPO_ROOT / "infra" / "heimdall" / "homepage"

SERVICE_GROUPS = {
    "Website": "Public",
    "Demo Apps": "Public",
    "Homepage": "Public",
    "Heimdall": "Public",
    "Service Catalog": "Public",
    "Gitea": "Platform",
    "Argo CD": "Platform",
    "Grafana": "Platform",
    "Prometheus": "Platform",
    "Alertmanager": "Platform",
    "Provisioning PXE": "Platform",
    "PXE Rescue": "Platform",
    "Container Registry": "Platform",
    "Matrix": "Communication",
    "Element": "Communication",
    "n8n": "Automation",
    "Pi-hole": "Infrastructure",
    "Uptime Kuma": "Infrastructure",
    "Blockchain Explorer": "Labs",
    "Prowlarr": "Media",
    "Sonarr": "Media",
    "Radarr": "Media",
    "qBittorrent": "Media",
    "Kapowarr": "Media",
    "Suwayomi": "Media",
    "Maintainerr": "Media",
    "FlareSolverr": "Media",
    "Jellyfin": "Media",
}

GROUP_ORDER = (
    "Public",
    "Platform",
    "Infrastructure",
    "Devices",
    "Media",
    "Communication",
    "Automation",
    "Labs",
    "Other",
)

ICON_MAP = {
    "Website": "mdi-web",
    "Demo Apps": "mdi-test-tube",
    "Homepage": "homepage.png",
    "Heimdall": "heimdall.png",
    "Service Catalog": "mdi-map",
    "Gitea": "gitea.png",
    "Argo CD": "argocd.png",
    "Grafana": "grafana.png",
    "Prometheus": "prometheus.png",
    "Alertmanager": "prometheus.png",
    "Provisioning PXE": "mdi-lan-connect",
    "PXE Rescue": "mdi-lifebuoy",
    "Container Registry": "docker.png",
    "Pi-hole": "pi-hole.png",
    "Uptime Kuma": "uptime-kuma.png",
    "Matrix": "matrix.png",
    "Element": "element.png",
    "n8n": "n8n.png",
    "Prowlarr": "prowlarr.png",
    "Sonarr": "sonarr.png",
    "Radarr": "radarr.png",
    "qBittorrent": "qbittorrent.png",
    "Kapowarr": "mdi-book-open-page-variant",
    "Suwayomi": "mdi-book-open-variant",
    "Maintainerr": "maintainerr.png",
    "FlareSolverr": "mdi-cloud-refresh",
    "Jellyfin": "jellyfin.png",
    "Blockchain Explorer": "mdi-cube-outline",
}


def parse_inventory(path: pathlib.Path) -> dict[str, Any]:
    values: dict[str, Any] = {}
    stack: list[tuple[int, str]] = []
    current_list_path: str | None = None
    pattern = re.compile(r"^(\s*)([A-Za-z_][A-Za-z0-9_]*):(?:\s*(.*?))?\s*$")

    with path.open(encoding="utf-8") as handle:
        for raw_line in handle:
            stripped = raw_line.strip()
            if not stripped or stripped.startswith("#"):
                continue
            if stripped.startswith("- "):
                if current_list_path:
                    values.setdefault(current_list_path, [])
                    values[current_list_path].append(clean_value(stripped[2:]))
                continue

            match = pattern.match(raw_line.rstrip("\n"))
            if not match:
                current_list_path = None
                continue

            indent = len(match.group(1))
            key = match.group(2)
            value = (match.group(3) or "").strip()
            while stack and stack[-1][0] >= indent:
                stack.pop()
            path_key = ".".join([item[1] for item in stack] + [key])
            if value == "":
                stack.append((indent, key))
                current_list_path = path_key
                continue
            values[path_key] = clean_value(value)
            current_list_path = None
    return values


def clean_value(value: str) -> str:
    if " #" in value:
        value = value.split(" #", 1)[0]
    return value.strip().strip('"\'')


def value(values: dict[str, Any], path: str, default: str = "") -> str:
    raw_value = values.get(path, default)
    if isinstance(raw_value, list):
        return ", ".join(str(item) for item in raw_value)
    return str(raw_value)


def yaml_scalar(text: str) -> str:
    return json.dumps(str(text))


def service_item(name: str, href: str, description: str, icon: str = "", ping: str = "") -> dict[str, str]:
    item = {
        "name": name,
        "href": href,
        "description": description,
    }
    if icon:
        item["icon"] = icon
    if ping:
        item["ping"] = ping
    return item


def load_heimdall_links() -> list[dict[str, str]]:
    if not HEIMDALL_LINKS.exists():
        return []
    with HEIMDALL_LINKS.open(encoding="utf-8") as handle:
        return json.load(handle)


def homepage_link(values: dict[str, Any]) -> dict[str, str]:
    public_url = value(values, "services.homepage.public_url", f"https://homepage.{value(values, 'domain.base')}/")
    return {
        "title": "Homepage",
        "url": public_url,
        "description": "Generated homelab operations dashboard",
        "class": "Homepage",
    }


def generated_services(values: dict[str, Any]) -> dict[str, list[dict[str, str]]]:
    groups = {group: [] for group in GROUP_ORDER}
    links = [homepage_link(values), *load_heimdall_links()]

    seen: set[str] = set()
    for link in links:
        title = link["title"].strip()
        if not title or title.lower() in seen:
            continue
        seen.add(title.lower())
        group = SERVICE_GROUPS.get(title, "Other")
        groups[group].append(
            service_item(
                title,
                link["url"],
                link.get("description", ""),
                ICON_MAP.get(title, ""),
            )
        )

    for device in device_services(values):
        groups["Devices"].append(device)

    return {group: items for group, items in groups.items() if items}


def device_services(values: dict[str, Any]) -> list[dict[str, str]]:
    debian_ip = value(values, "hosts.debian.lan_ip")
    debian_ts = value(values, "hosts.debian.tailscale_ip")
    edge_ip = value(values, "hosts.oci_edge.public_ip")
    edge_ts = value(values, "hosts.oci_edge.tailscale_ip")
    pimox_ip = value(values, "hosts.opi5_pimox.lan_ip")
    worker_count = int(value(values, "pimox.default_worker_count", "0") or "0")
    worker_prefix = value(values, "pimox.worker_name_prefix", "pimox-worker")
    worker_base_vmid = int(value(values, "pimox.worker_base_vmid", "9010") or "9010")

    devices = [
        service_item(
            "Debian Laptop",
            f"http://{debian_ip}:8088/",
            f"Control plane, Docker host, Gitea, and provisioning server. Tailscale: {debian_ts}",
            "debian.png",
            debian_ip,
        ),
        service_item(
            "OCI Edge Server",
            f"https://{value(values, 'domain.base')}/edge-health",
            f"Public Nginx/HAProxy/Varnish/Squid edge. Public: {edge_ip}; Tailscale: {edge_ts}",
            "nginx.png",
            edge_ip,
        ),
        service_item(
            "Pimox Hypervisor",
            f"https://{pimox_ip}:8006/",
            "Orange Pi 5 Pimox host for Kubernetes worker VMs",
            "proxmox.png",
            pimox_ip,
        ),
    ]

    for index in range(1, worker_count + 1):
        worker_name = f"{worker_prefix}-{index:02d}"
        vmid = worker_base_vmid + index - 1
        devices.append(
            service_item(
                worker_name,
                f"ssh://{worker_name}",
                f"Pimox Kubernetes worker VMID {vmid}",
                "kubernetes.png",
                worker_name,
            )
        )
    return devices


def render_services(groups: dict[str, list[dict[str, str]]]) -> str:
    lines: list[str] = []
    for group, items in groups.items():
        lines.append(f"- {group}:")
        for item in items:
            lines.append(f"    - {item['name']}:")
            lines.append(f"        href: {yaml_scalar(item['href'])}")
            lines.append(f"        description: {yaml_scalar(item['description'])}")
            if item.get("icon"):
                lines.append(f"        icon: {yaml_scalar(item['icon'])}")
            if item.get("ping"):
                lines.append(f"        ping: {yaml_scalar(item['ping'])}")
        lines.append("")
    return "\n".join(lines).rstrip() + "\n"


def render_bookmarks(values: dict[str, Any]) -> str:
    repo_url = value(values, "services.gitea.root_url", value(values, "domain.gitea_url"))
    public_url = value(values, "domain.public_url")
    return "\n".join(
        [
            "- Homelab:",
            "    - Repo:",
            f"        - abbr: GH",
            f"          href: {yaml_scalar(repo_url)}",
            "    - Public site:",
            f"        - abbr: HL",
            f"          href: {yaml_scalar(public_url)}",
            "",
            "- Runbooks:",
            "    - Edge failures:",
            "        - abbr: ED",
            "          href: https://demos.lab2025.duckdns.org/homelab-catalog/",
            "",
        ]
    )


def render_settings(values: dict[str, Any]) -> str:
    return "\n".join(
        [
            f"title: {yaml_scalar('Homelab')}",
            "theme: dark",
            "color: slate",
            "layout:",
            "  Public:",
            "    style: row",
            "    columns: 4",
            "  Platform:",
            "    style: row",
            "    columns: 4",
            "  Infrastructure:",
            "    style: row",
            "    columns: 4",
            "  Devices:",
            "    style: row",
            "    columns: 4",
            "  Media:",
            "    style: row",
            "    columns: 4",
            "",
        ]
    )


def render_widgets(values: dict[str, Any]) -> str:
    return "\n".join(
        [
            "- datetime:",
            "    text_size: xl",
            "    format:",
            "      dateStyle: long",
            "      timeStyle: short",
            "- resources:",
            "    cpu: true",
            "    memory: true",
            "    disk: /",
            "",
        ]
    )


def write_if_changed(path: pathlib.Path, content: str) -> bool:
    if path.exists() and path.read_text(encoding="utf-8") == content:
        return False
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(content, encoding="utf-8")
    return True


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--output-dir", type=pathlib.Path, default=OUTPUT_DIR)
    parser.add_argument("--check", action="store_true", help="fail if generated files are stale")
    args = parser.parse_args()

    values = parse_inventory(INVENTORY)
    outputs = {
        "services.yaml": render_services(generated_services(values)),
        "bookmarks.yaml": render_bookmarks(values),
        "settings.yaml": render_settings(values),
        "widgets.yaml": render_widgets(values),
    }

    stale = []
    for name, content in outputs.items():
        path = args.output_dir / name
        if args.check:
            current = path.read_text(encoding="utf-8") if path.exists() else ""
            if current != content:
                stale.append(str(path.relative_to(REPO_ROOT)))
        else:
            write_if_changed(path, content)

    if stale:
        print("Homepage config is stale; run scripts/generate-homepage-config:")
        for path in stale:
            print(f"  {path}")
        return 1

    if not args.check:
        print(f"Generated Homepage config in {args.output_dir.relative_to(REPO_ROOT)}")
    return 0


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