#!/usr/bin/env python3
"""Generate Heimdall dashboard links from repo service discovery metadata."""

from __future__ import annotations

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

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

DEFAULT_COLOUR = "#334155"

ARR_LOCAL_SERVICES = (
    ("prowlarr", "services.arr.prowlarr_port", "9696"),
    ("sonarr", "services.arr.sonarr_port", "8989"),
    ("radarr", "services.arr.radarr_port", "7878"),
    ("qbittorrent", "services.arr.qbittorrent_port", "8080"),
    ("kapowarr", "services.arr.kapowarr_port", "5656"),
    ("suwayomi", "services.arr.suwayomi_port", "4567"),
    ("maintainerr", "services.arr.maintainerr_port", "6246"),
)

LOCAL_DASHBOARD_HOST_PREFIXES = {name for name, _port_path, _default in ARR_LOCAL_SERVICES}

HOST_METADATA = {
    "lab2025": ("Website", "Public portfolio website", "#0f766e", "Website"),
    "demos": ("Demo Apps", "Static browser-side demo catalog", "#2563eb", "Demos"),
    "heimdall": ("Heimdall", "Homelab service dashboard", "#7c3aed", "Heimdall"),
    "homepage": ("Homepage", "Generated homelab operations dashboard", "#0284c7", "Homepage"),
    "jellyfin": ("Jellyfin", "Media streaming server", "#7c3aed", "Jellyfin"),
    "auth": ("Dex", "Homelab OpenID Connect SSO provider", "#2563eb", "Dex"),
    "matrix": ("Matrix", "Matrix Synapse homeserver", "#0f172a", "Matrix"),
    "element": ("Element", "Matrix web client", "#0ea5e9", "Element"),
    "grafana": ("Grafana", "Monitoring dashboards", "#f97316", "Grafana"),
    "prometheus": ("Prometheus", "Prometheus query UI", "#dc2626", "Prometheus"),
    "alertmanager": ("Alertmanager", "Alert routing and silences", "#b91c1c", "Alertmanager"),
    "argocd": ("Argo CD", "GitOps application sync status", "#0ea5e9", "ArgoCD"),
    "n8n": ("n8n", "Workflow automation for translation jobs and homelab tasks", "#ea4b71", "N8N"),
    "prowlarr": ("Prowlarr", "Indexer management for the media automation stack", "#2563eb", "Prowlarr"),
    "sonarr": ("Sonarr", "TV library automation", "#22c55e", "Sonarr"),
    "radarr": ("Radarr", "Movie library automation", "#f59e0b", "Radarr"),
    "qbittorrent": ("qBittorrent", "Torrent download client", "#3b82f6", "Qbittorrent"),
    "kapowarr": ("Kapowarr", "Comics library automation", "#ef4444", "Kapowarr"),
    "suwayomi": ("Suwayomi", "Manga server and scraper engine", "#8b5cf6", "Suwayomi"),
    "maintainerr": ("Maintainerr", "Media list maintenance automation", "#14b8a6", "Maintainerr"),
    "flaresolverr": ("FlareSolverr", "Browser challenge solver service for ARR automation", "#64748b", "FlareSolverr"),
    "search": ("SearXNG", "Privacy-respecting homelab metasearch", "#22a699", "SearXNG"),
    "paste": ("PrivateBin", "Browser-encrypted expiring paste service", "#4f46e5", "PrivateBin"),
    "feeds": ("Miniflux", "Private RSS reader with tracker filtering", "#f97316", "Miniflux"),
}


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:
                    if not isinstance(values.get(current_list_path), list):
                        values[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))
                values.setdefault(path_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)
    if isinstance(raw_value, dict):
        return default
    return str(raw_value)


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


def host_ip(values: dict[str, Any], host_name: str, default: str = "") -> str:
    return value(values, f"hosts.{host_name}.lan_ip", default)


def expand_placeholders(text: str, values: dict[str, Any], compose_dir: pathlib.Path) -> str:
    host_defaults = {
        "debian": host_ip(values, "debian"),
        "rpi4": host_ip(values, "rpi4"),
        "traefik": value(values, "network.metallb.traefik_ip"),
    }
    for host_name, ip in host_defaults.items():
        text = text.replace(f"${{{host_name}.lan_ip}}", ip)
        text = text.replace(f"{{{host_name}.lan_ip}}", ip)
    text = text.replace("${compose_dir}", str(compose_dir))
    text = text.replace("{compose_dir}", str(compose_dir))

    def replace_env(match: re.Match[str]) -> str:
        name = match.group(1)
        default = match.group(2) or ""
        return os.environ.get(name, default)

    text = re.sub(r"\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\}", replace_env, text)
    return text


def title_from_host(hostname: str, base_domain: str) -> str:
    if hostname == base_domain:
        return HOST_METADATA["lab2025"][0]
    prefix = hostname.removesuffix(f".{base_domain}").split(".")[-1]
    return HOST_METADATA.get(prefix, (prefix.replace("-", " ").title(), "", DEFAULT_COLOUR, prefix.title()))[0]


def link(title: str, url: str, description: str = "", colour: str = DEFAULT_COLOUR, class_name: str = "") -> dict[str, str]:
    item = {
        "title": title,
        "url": url,
        "description": description,
        "colour": colour,
        "class": class_name or re.sub(r"[^A-Za-z0-9]", "", title),
    }
    return item


def public_links(values: dict[str, Any]) -> list[dict[str, str]]:
    base_domain = value(values, "domain.base")
    hosts = [base_domain, *list_value(values, "domain.subdomains")]
    links: list[dict[str, str]] = []
    for hostname in hosts:
        if not hostname:
            continue
        prefix = "lab2025" if hostname == base_domain else hostname.removesuffix(f".{base_domain}").split(".")[-1]
        if prefix in LOCAL_DASHBOARD_HOST_PREFIXES:
            continue
        title, description, colour, class_name = HOST_METADATA.get(
            prefix,
            (title_from_host(hostname, base_domain), "Public service exposed through DuckDNS", DEFAULT_COLOUR, prefix.title()),
        )
        links.append(link(title, f"https://{hostname}/", description, colour, class_name))
    return links


def inventory_links(values: dict[str, Any]) -> list[dict[str, str]]:
    debian_ip = host_ip(values, "debian", "192.168.100.73")
    rpi_ip = host_ip(values, "rpi4", "192.168.100.89")
    registry = value(values, "services.local_registry.endpoint", f"{debian_ip}:30500")
    links = [
        link(
            "Service Catalog",
            f"https://demos.{value(values, 'domain.base')}/homelab-catalog/",
            "Generated host, service, route, and runbook map from homelab.yml",
            "#0891b2",
            "Catalog",
        ),
        link(
            "Provisioning PXE",
            f"http://{debian_ip}:{value(values, 'services.provisioning.http_port', '8088')}/",
            "PXE, preseed, and worker provisioning HTTP files",
            "#0d9488",
            "Provisioning",
        ),
        link(
            "PXE Rescue",
            value(values, "services.provisioning.rescue_url", f"http://{debian_ip}:8088/rescue/"),
            "Browser rescue toolkit for manual repair paths",
            "#0f766e",
            "Rescue",
        ),
        link(
            "Gitea",
            value(values, "services.gitea.root_url"),
            "External Git service on the Debian host",
            "#609926",
            "Gitea",
        ),
        link(
            "Container Registry",
            f"http://{registry}/v2/_catalog",
            "Local image registry catalog endpoint",
            "#334155",
            "Docker",
        ),
        link(
            "Pi-hole",
            f"http://{rpi_ip}:{value(values, 'services.rpi_dns.pihole_web_port', '8081')}/admin/",
            "LAN DNS and ad blocking on the Raspberry Pi",
            "#dc2626",
            "PiHole",
        ),
        link(
            "Uptime Kuma",
            f"http://{rpi_ip}:{value(values, 'services.rpi_dns.uptime_kuma_port', '3001')}/",
            "Service uptime checks on the Raspberry Pi",
            "#16a34a",
            "UptimeKuma",
        ),
        link(
            "Blockchain Explorer",
            f"http://{debian_ip}:8089/",
            "Optional local Ethereum devnet explorer",
            "#9333ea",
            "Blockchain",
        ),
    ]

    for name, port_path, default_port in ARR_LOCAL_SERVICES:
        title, description, colour, class_name = HOST_METADATA[name]
        links.append(
            link(
                title,
                f"http://{debian_ip}:{value(values, port_path, default_port)}/",
                description,
                colour,
                class_name,
            )
        )

    return links


def parse_labeled_block(block: str, prefix: str) -> dict[str, str]:
    labels: dict[str, str] = {}
    for raw_line in block.splitlines():
        line = raw_line.strip()
        if line.startswith("-"):
            line = line[1:].strip().strip('"\'')
            if line.startswith(prefix) and "=" in line:
                key, value_text = line.split("=", 1)
                labels[key.removeprefix(prefix)] = clean_value(value_text)
            continue
        if line.startswith(prefix) and ":" in line:
            key, value_text = line.split(":", 1)
            labels[key.removeprefix(prefix)] = clean_value(value_text)
    return labels


def compose_links(values: dict[str, Any]) -> list[dict[str, str]]:
    links: list[dict[str, str]] = []
    for compose_path in sorted((REPO_ROOT / "infra").glob("*/docker-compose.yml")):
        text = compose_path.read_text(encoding="utf-8")
        for labels in find_compose_labels(text):
            if labels.get("enabled", "false").lower() != "true":
                continue
            title = labels.get("title")
            url = labels.get("url")
            if not title or not url:
                continue
            links.append(
                link(
                    title,
                    expand_placeholders(url, values, compose_path.parent),
                    labels.get("description", "Docker Compose service"),
                    labels.get("colour", DEFAULT_COLOUR),
                    labels.get("class", title),
                )
            )
    return links


def find_compose_labels(text: str) -> list[dict[str, str]]:
    labels: list[dict[str, str]] = []
    lines = text.splitlines()
    service_indexes: list[int] = []
    for index, line_text in enumerate(lines):
        if re.match(r"^  [A-Za-z0-9_.-]+:\s*$", line_text):
            service_indexes.append(index)
    service_indexes.append(len(lines))
    for start, end in zip(service_indexes, service_indexes[1:]):
        block = "\n".join(lines[start:end])
        found = parse_labeled_block(block, "homelab.heimdall.")
        if found:
            labels.append(found)
    return labels


def kubernetes_links(values: dict[str, Any]) -> list[dict[str, str]]:
    links: list[dict[str, str]] = []
    base_domain = value(values, "domain.base")
    for manifest_path in sorted((REPO_ROOT / "apps").glob("**/*.yaml")):
        text = manifest_path.read_text(encoding="utf-8")
        links.extend(annotated_manifest_links(text, values, manifest_path.parent))
        for hostname in re.findall(r"\bhost:\s*([A-Za-z0-9_.-]+)\s*", text):
            prefix = hostname.removesuffix(f".{base_domain}").split(".")[-1]
            title, description, colour, class_name = HOST_METADATA.get(
                prefix,
                (title_from_host(hostname, base_domain), "Kubernetes Ingress exposed through DuckDNS", DEFAULT_COLOUR, prefix.title()),
            )
            links.append(link(title, f"https://{hostname}/", description, colour, class_name))
    return links


def annotated_manifest_links(text: str, values: dict[str, Any], manifest_dir: pathlib.Path) -> list[dict[str, str]]:
    links: list[dict[str, str]] = []
    for document in re.split(r"^---\s*$", text, flags=re.MULTILINE):
        labels = parse_labeled_block(document.replace("homelab.heimdall/", "homelab.heimdall."), "homelab.heimdall.")
        if labels.get("enabled", "false").lower() != "true":
            continue
        title = labels.get("title")
        url = labels.get("url")
        if not title or not url:
            continue
        links.append(
            link(
                title,
                expand_placeholders(url, values, manifest_dir),
                labels.get("description", "Kubernetes service"),
                labels.get("colour", DEFAULT_COLOUR),
                labels.get("class", title),
            )
        )
    return links


def merge_links(*groups: list[dict[str, str]]) -> list[dict[str, str]]:
    merged: list[dict[str, str]] = []
    seen_urls: set[str] = set()
    seen_titles: set[str] = set()
    for group in groups:
        for item in group:
            title = item["title"].strip()
            url = item["url"].strip()
            if not title or not url or url in seen_urls or title.lower() in seen_titles:
                continue
            item["title"] = title
            item["url"] = url
            merged.append(item)
            seen_urls.add(url)
            seen_titles.add(title.lower())
    return merged


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--output", type=pathlib.Path, default=OUTPUT)
    parser.add_argument("--check", action="store_true", help="fail if the output file is stale")
    args = parser.parse_args()

    values = parse_inventory(INVENTORY)
    generated = merge_links(
        public_links(values),
        inventory_links(values),
        kubernetes_links(values),
        compose_links(values),
    )
    rendered = json.dumps(generated, indent=2) + "\n"

    if args.check:
        current = args.output.read_text(encoding="utf-8") if args.output.exists() else ""
        if current != rendered:
            print(f"{args.output} is stale; run scripts/generate-heimdall-links", flush=True)
            return 1
        return 0

    args.output.parent.mkdir(parents=True, exist_ok=True)
    args.output.write_text(rendered, encoding="utf-8")
    print(f"Generated {args.output.relative_to(REPO_ROOT)} with {len(generated)} links")
    return 0


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