"""Passive local service checks over the dashboard's configured service list."""

from collections import Counter
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timezone
import json
import os
from pathlib import Path
import re
import subprocess


class ServiceConfigError(ValueError):
    """A configuration error safe to show to an MCP client."""


class HomeAdapter:
    PROPERTIES = {"LoadState": "load_state", "ActiveState": "active_state",
                  "SubState": "sub_state", "Result": "result"}

    def __init__(self, config_path: Path, *, runner=None):
        self.config_path = config_path
        self.runner = runner or subprocess.run

    def _services(self):
        try:
            if self.config_path.stat().st_size > 1024 * 1024:
                raise ServiceConfigError("Service configuration exceeds the development size limit.")
            config = json.loads(self.config_path.read_text())
        except (OSError, ValueError):
            raise ServiceConfigError("Cannot read the local services configuration.") from None
        rows = config.get("services") if isinstance(config, dict) else None
        if not isinstance(rows, list) or not 1 <= len(rows) <= 64:
            raise ServiceConfigError("Configure between 1 and 64 services.")
        services, seen = [], set()
        for row in rows:
            if not isinstance(row, dict):
                raise ServiceConfigError("Invalid service entry.")
            service_id = row.get("id")
            if not isinstance(service_id, str) or not re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}", service_id) or service_id in seen:
                raise ServiceConfigError("Service IDs must be unique short identifiers.")
            seen.add(service_id)
            unit = row.get("systemd_unit")
            if unit is not None and (not isinstance(unit, str) or not re.fullmatch(r"[a-zA-Z0-9_][a-zA-Z0-9_.@:-]*\.(?:service|socket)", unit) or len(unit) > 255):
                raise ServiceConfigError("Invalid configured systemd unit.")
            scope = row.get("systemd_scope") or "system"
            if scope not in {"system", "user"}:
                raise ServiceConfigError("Invalid systemd scope.")
            ports = row.get("ports") or []
            if not isinstance(ports, list) or len(ports) > 16 or any(type(p) is not int or not 1 <= p <= 65535 for p in ports):
                raise ServiceConfigError("Invalid configured TCP ports.")
            primary = row.get("primary_port")
            if primary is not None and (type(primary) is not int or primary not in ports):
                raise ServiceConfigError("The primary port must be in the configured port list.")
            expected = row.get("expected_active", True)
            if not isinstance(expected, bool):
                raise ServiceConfigError("expected_active must be a boolean.")
            services.append({"id": service_id, "name": str(row.get("name") or service_id)[:100],
                             "unit": unit, "scope": scope, "ports": list(dict.fromkeys(ports)),
                             "primary_port": primary, "expected_active": expected})
        return services

    def _run(self, command):
        # Fixed executables and arguments only. Keep environment/credentials and
        # process command lines out of results. No HTTP requests or shell.
        runtime = f"/run/user/{os.getuid()}"
        env = {"PATH": "/usr/bin:/bin", "LC_ALL": "C", "SYSTEMD_COLORS": "0",
               "SYSTEMD_PAGER": "cat", "XDG_RUNTIME_DIR": runtime,
               "DBUS_SESSION_BUS_ADDRESS": f"unix:path={runtime}/bus"}
        try:
            result = self.runner(command, capture_output=True, text=True,
                                 timeout=2, check=False, env=env)
        except (OSError, subprocess.TimeoutExpired):
            return None, "Local status command is unavailable or timed out."
        # ss can exit 0 while reporting a denied netlink operation on stderr.
        if result.returncode != 0 or result.stderr.strip():
            return None, "Local status could not be inspected; check host permissions and service-manager access."
        if len(result.stdout) > 1024 * 1024:
            return None, "Local status output exceeded the development size limit."
        return result.stdout, None

    def _listeners(self):
        output, error = self._run(["/usr/bin/ss", "-H", "-ltn"])
        if error:
            return None, error
        ports = set()
        for line in output.splitlines():
            fields = line.split()
            if len(fields) < 5 or fields[0] != "LISTEN":
                return None, "Unrecognized local TCP listener output."
            try:
                ports.add(int(fields[3].rsplit(":", 1)[1]))
            except (ValueError, IndexError):
                return None, "Unrecognized local TCP listener output."
        return ports, None

    def _unit(self, service):
        if not service["unit"]:
            return None
        command = ["/usr/bin/systemctl"]
        if service["scope"] == "user":
            command.append("--user")
        command.extend(["show", service["unit"], "--no-pager",
                        "--property=" + ",".join(self.PROPERTIES)])
        output, error = self._run(command)
        result = {"unit": service["unit"], "scope": service["scope"], "available": not bool(error)}
        if error:
            return {**result, "error": error}
        for line in output.splitlines():
            key, _, value = line.partition("=")
            if key in self.PROPERTIES:
                result[self.PROPERTIES[key]] = value[:80]
        if "load_state" not in result or "active_state" not in result:
            return {"unit": service["unit"], "scope": service["scope"], "available": False,
                    "error": "Incomplete service-manager response."}
        return result

    @staticmethod
    def _state(service, unit, ports):
        if not unit and not ports:
            return "not_monitored", "No local unit or TCP port is configured."
        required = [p for p in ports if p["primary"]] or ports
        listening = any(p["listening"] is True for p in required)
        missing = any(p["listening"] is False for p in required)
        if unit and unit["available"] and unit["active_state"] in {"inactive", "failed"}:
            if listening:
                return "degraded", "Unit is inactive/failed, but a configured port has a listener."
            return ("not_running" if service["expected_active"] else "stopped"), "Unit is inactive or failed."
        if (unit and not unit["available"]) or any(p["listening"] is None for p in required):
            return "unknown", "Some local checks are unavailable."
        if unit and unit["active_state"] != "active":
            return "unknown", "Unit is transitioning or has an unrecognized active state."
        if missing:
            if unit:
                return "degraded", "Unit is active, but a required TCP listener is absent."
            return ("not_running" if service["expected_active"] else "stopped"), "Configured TCP listener is absent."
        if unit:
            return "running", "Unit is active; configured primary TCP listener is present." if required else "Unit is active."
        return "listening", "Configured TCP listener is present."

    def status(self, service_id=None):
        services = self._services()
        if service_id is not None:
            services = [service for service in services if service["id"] == service_id]
            if not services:
                raise ServiceConfigError("Unknown service ID. Omit service_id to list the configured services.")
        checked_at = datetime.now(timezone.utc).isoformat()
        with ThreadPoolExecutor(max_workers=8) as pool:
            listeners = pool.submit(self._listeners) if any(s["ports"] for s in services) else None
            units = [pool.submit(self._unit, service) for service in services]
            port_set, port_error = listeners.result() if listeners else (set(), None)
            results = []
            for service, task in zip(services, units):
                unit = task.result()
                ports = [{"port": port, "primary": port == service["primary_port"],
                          "listening": port in port_set if port_set is not None else None}
                         for port in service["ports"]]
                state, reason = self._state(service, unit, ports)
                result = {"id": service["id"], "name": service["name"], "status": state,
                          "reason": reason, "expected_active": service["expected_active"],
                          "systemd": unit, "tcp_ports": ports}
                if ports and port_error:
                    result["port_check_error"] = port_error
                results.append(result)
        return {"checked_at": checked_at, "read_only": True, "services": results,
                "summary": dict(Counter(item["status"] for item in results)),
                "note": "Local systemd state and TCP listener presence only. Does not verify listener ownership, application responses or public URLs. No services are started/restarted and no network probes are sent."}
