#!/usr/bin/env python3
from __future__ import annotations

import json
import os
import shutil
import subprocess
import sys
from pathlib import Path
from urllib.request import urlopen, Request

ROOT = Path("/home/sebas/pi-config")
HOME = Path("/home/sebas")
REQUIRED_DIRS = [
    HOME / "agents-database",
    HOME / "runtime",
    HOME / "work",
    HOME / "outputs",
    HOME / "archive",
    HOME / "notes",
]
REQUIRED_FILES = [
    ROOT / "settings.json",
    ROOT / "AGENTS.md",
    ROOT / "docs/bootstrap.md",
    ROOT / "docs/service-manifest.md",
    ROOT / "docs/backup-policy.md",
    ROOT / "bin/task-phase-init",
    ROOT / "bin/task-phase-run",
    ROOT / "bin/task-phase-loop",
    ROOT / "scripts/bootstrap-prereqs.sh",
    ROOT / "scripts/bootstrap-pi-config.sh",
    ROOT / "scripts/bootstrap-services.sh",
    ROOT / "scripts/bootstrap-validate.sh",
]
URLS = {
    "agents_database": "http://100.116.176.16:8091/api/status",
}
USER_UNITS = [
    "agents-database-http.service",
    "agents-database-maintenance.service",
    "install-session-memory-dispatcher.service",
    "session-memory-sweeper.timer",
    "pi-telegram.service",
    "wifi-tracker-api.service",
]
SYSTEM_PATHS = [
    Path("/etc/nginx/sites-available/kiosk"),
    Path("/var/www/portal/index.html"),
]


def run(cmd: list[str]) -> tuple[int, str]:
    p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
    return p.returncode, p.stdout.strip()


def check_url(url: str) -> tuple[bool, str]:
    try:
        req = Request(url, headers={"User-Agent": "pi-config-audit"})
        with urlopen(req, timeout=5) as resp:
            body = resp.read(300).decode("utf-8", "replace")
        return True, body
    except Exception as e:
        return False, str(e)


def main() -> int:
    issues: list[str] = []
    warnings: list[str] = []
    info: list[str] = []

    for cmd in ["pi", "bun", "python3", "tmux", "git", "curl"]:
        path = shutil.which(cmd)
        if path:
            info.append(f"cmd ok: {cmd} -> {path}")
        else:
            issues.append(f"missing command: {cmd}")

    path_env = os.environ.get("PATH", "")
    for expected in ["/home/sebas/pi-config/bin", "/home/sebas/.local/bin"]:
        if expected in path_env.split(":"):
            info.append(f"path ok: {expected}")
        else:
            warnings.append(f"PATH missing expected entry: {expected}")

    for d in REQUIRED_DIRS:
        if d.is_dir():
            info.append(f"dir ok: {d}")
        else:
            issues.append(f"missing dir: {d}")

    for f in REQUIRED_FILES:
        if f.exists():
            info.append(f"file ok: {f}")
        else:
            issues.append(f"missing file: {f}")

    for label, url in URLS.items():
        ok, detail = check_url(url)
        if ok:
            info.append(f"url ok: {label} -> {url}")
        else:
            issues.append(f"url failed: {label} -> {url} ({detail})")

    for unit in USER_UNITS:
        code, out = run(["systemctl", "--user", "is-enabled", unit])
        if code == 0:
            info.append(f"user unit enabled: {unit}")
        else:
            warnings.append(f"user unit not enabled: {unit} ({out})")

    for p in SYSTEM_PATHS:
        if p.exists():
            info.append(f"host path ok: {p}")
        else:
            warnings.append(f"host path missing: {p}")

    tmux_conf = HOME / ".tmux.conf"
    if tmux_conf.exists():
        info.append(f"tmux config ok: {tmux_conf}")
    else:
        warnings.append(f"tmux config missing: {tmux_conf}")

    print("pi-config audit")
    print(f"root={ROOT}")
    print()
    print("issues:")
    if issues:
        for item in issues:
            print(f"- {item}")
    else:
        print("- none")
    print()
    print("warnings:")
    if warnings:
        for item in warnings:
            print(f"- {item}")
    else:
        print("- none")
    print()
    print("info:")
    for item in info:
        print(f"- {item}")

    return 1 if issues else 0


if __name__ == "__main__":
    sys.exit(main())
