#!/usr/bin/env python3

from __future__ import annotations

import argparse
import json
import os
import re
import stat
import subprocess
import sys
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Any, Sequence


PROJECT_ROOT = Path(
    os.environ.get(
        "FIVEBR_INFRA_ROOT",
        "/opt/5ibr-infra",
    )
)
PACKAGE_MODE = (
    os.environ.get(
        "FIVEBR_INFRA_PACKAGE_MODE",
        "",
    ).strip().lower()
    in {"1", "true", "yes", "on"}
)
PACKAGE_NAME = "5ibr-infra"

BASELINE_PATH = (
    PROJECT_ROOT
    / "configs"
    / "production"
    / "baseline.json"
)
VERSION_PATH = PROJECT_ROOT / "VERSION"

HEALTHCHECK_PATH = (
    PROJECT_ROOT
    / "scripts"
    / "validation"
    / "5ibr-healthcheck.py"
)
STATUS_SCRIPT = PROJECT_ROOT / "scripts" / "status.sh"
PRUNE_SCRIPT = (
    PROJECT_ROOT
    / "scripts"
    / "prune-runtime-data.py"
)
FLEET_CLI_PATH = (
    PROJECT_ROOT
    / "scripts"
    / "fleet"
    / "5ibr-fleet"
)

VERSION_PATTERN = re.compile(
    r"^[0-9]+\.[0-9]+\.[0-9]+"
    r"(?:[-+][0-9A-Za-z.-]+)?$"
)


@dataclass(frozen=True)
class Check:
    name: str
    status: str
    message: str
    details: dict[str, Any]


@dataclass(frozen=True)
class CommandResult:
    code: int
    stdout: str
    stderr: str


def run_command(
    command: Sequence[str],
    *,
    timeout: int = 120,
    cwd: Path | None = None,
) -> CommandResult:
    try:
        completed = subprocess.run(
            list(command),
            check=False,
            capture_output=True,
            text=True,
            timeout=timeout,
            cwd=cwd,
        )
    except subprocess.TimeoutExpired as exc:
        stdout = (
            exc.stdout
            if isinstance(exc.stdout, str)
            else ""
        )
        stderr = (
            exc.stderr
            if isinstance(exc.stderr, str)
            else ""
        )

        return CommandResult(
            code=124,
            stdout=stdout,
            stderr=(
                stderr
                or f"Command timed out after {timeout}s"
            ),
        )
    except OSError as exc:
        return CommandResult(
            code=127,
            stdout="",
            stderr=str(exc),
        )

    return CommandResult(
        code=completed.returncode,
        stdout=completed.stdout.strip(),
        stderr=completed.stderr.strip(),
    )


def load_json_object(path: Path) -> dict[str, Any]:
    data = json.loads(
        path.read_text(encoding="utf-8")
    )

    if not isinstance(data, dict):
        raise ValueError(
            f"Expected JSON object in {path}"
        )

    return data


def check_baseline() -> Check:
    if not BASELINE_PATH.is_file():
        return Check(
            name="baseline",
            status="FAILED",
            message="Production baseline is missing",
            details={"path": str(BASELINE_PATH)},
        )

    try:
        data = load_json_object(BASELINE_PATH)
    except (
        OSError,
        UnicodeError,
        json.JSONDecodeError,
        ValueError,
    ) as exc:
        return Check(
            name="baseline",
            status="FAILED",
            message=f"Invalid production baseline: {exc}",
            details={"path": str(BASELINE_PATH)},
        )

    required = {
        "schema_version",
        "project",
        "local_units",
        "local_template_units",
        "remote_units",
        "external_integrations",
        "runtime_root",
        "repository_root",
        "expected_file_modes",
    }

    missing = sorted(required - data.keys())

    return Check(
        name="baseline",
        status="OK" if not missing else "FAILED",
        message=(
            "Production baseline is valid"
            if not missing
            else "Missing baseline fields: "
            + ", ".join(missing)
        ),
        details={
            "path": str(BASELINE_PATH),
            "missing_fields": missing,
        },
    )


def check_version() -> Check:
    if not VERSION_PATH.is_file():
        return Check(
            name="version",
            status="FAILED",
            message="VERSION file is missing",
            details={"path": str(VERSION_PATH)},
        )

    version = VERSION_PATH.read_text(
        encoding="utf-8"
    ).strip()

    valid = bool(VERSION_PATTERN.fullmatch(version))

    return Check(
        name="version",
        status="OK" if valid else "FAILED",
        message=(
            f"VERSION={version}"
            if valid
            else f"Invalid VERSION value: {version!r}"
        ),
        details={"version": version},
    )


def check_package_state() -> Check:
    query = run_command(
        [
            "dpkg-query",
            "-W",
            "-f=${Status}\n${Version}",
            PACKAGE_NAME,
        ]
    )

    if query.code != 0:
        return Check(
            name="package_state",
            status="FAILED",
            message=(
                query.stderr
                or "Unable to inspect installed package"
            ),
            details={
                "package": PACKAGE_NAME,
                "exit_code": query.code,
            },
        )

    lines = query.stdout.splitlines()
    status = lines[0].strip() if lines else ""
    version = lines[1].strip() if len(lines) > 1 else ""

    if status != "install ok installed":
        return Check(
            name="package_state",
            status="FAILED",
            message=f"Unexpected package status: {status}",
            details={
                "package": PACKAGE_NAME,
                "status": status,
                "version": version,
            },
        )

    verify = run_command(
        [
            "dpkg",
            "--verify",
            PACKAGE_NAME,
        ]
    )

    modified = [
        line
        for line in verify.stdout.splitlines()
        if line.strip()
    ]

    ok = verify.code == 0 and not modified

    return Check(
        name="package_state",
        status="OK" if ok else "FAILED",
        message=(
            f"Installed package {version} verified"
            if ok
            else "Installed package files failed verification"
        ),
        details={
            "package": PACKAGE_NAME,
            "status": status,
            "version": version,
            "modified": modified,
            "verify_exit_code": verify.code,
            "verify_stderr": verify.stderr,
        },
    )


def check_git_state() -> Check:
    result = run_command(
        [
            "git",
            "status",
            "--short",
            "--branch",
        ],
        cwd=PROJECT_ROOT,
    )

    if result.code != 0:
        return Check(
            name="git_state",
            status="FAILED",
            message=(
                result.stderr
                or "Unable to inspect Git state"
            ),
            details={"exit_code": result.code},
        )

    lines = result.stdout.splitlines()
    changes = [
        line
        for line in lines[1:]
        if line.strip()
    ]

    return Check(
        name="git_state",
        status="OK" if not changes else "WARNING",
        message=(
            "Working tree is clean"
            if not changes
            else f"Working tree has {len(changes)} change(s)"
        ),
        details={
            "branch": lines[0] if lines else "",
            "changes": changes,
        },
    )


def expected_mode_for(
    git_mode: str,
    path: Path,
    baseline: dict[str, Any],
) -> int:
    modes = baseline.get(
        "expected_file_modes",
        {},
    )

    if path == Path(
        "scripts/security/5ibr-wings-firewall"
    ):
        value = str(
            modes.get(
                "security_firewall_script",
                "0750",
            )
        )
    elif git_mode == "100755":
        value = str(
            modes.get(
                "tracked_executable",
                "0755",
            )
        )
    else:
        value = str(
            modes.get(
                "tracked_regular",
                "0644",
            )
        )

    return int(value, 8)


def check_tracked_permissions(
    baseline: dict[str, Any],
) -> Check:
    result = run_command(
        ["git", "ls-files", "-s"],
        cwd=PROJECT_ROOT,
    )

    if result.code != 0:
        return Check(
            name="tracked_permissions",
            status="FAILED",
            message="Unable to list tracked files",
            details={
                "exit_code": result.code,
                "stderr": result.stderr,
            },
        )

    mismatches: list[dict[str, str]] = []
    missing: list[str] = []

    for line in result.stdout.splitlines():
        parts = line.split(maxsplit=3)

        if len(parts) != 4:
            continue

        git_mode, _, _, relative_name = parts
        relative_path = Path(relative_name)
        absolute_path = PROJECT_ROOT / relative_path

        if not absolute_path.exists():
            missing.append(relative_name)
            continue

        actual = stat.S_IMODE(
            absolute_path.stat().st_mode
        )
        expected = expected_mode_for(
            git_mode,
            relative_path,
            baseline,
        )

        if actual != expected:
            mismatches.append(
                {
                    "path": relative_name,
                    "actual": f"{actual:04o}",
                    "expected": f"{expected:04o}",
                }
            )

    ok = not mismatches and not missing

    return Check(
        name="tracked_permissions",
        status="OK" if ok else "FAILED",
        message=(
            "Tracked file permissions match baseline"
            if ok
            else (
                f"{len(mismatches)} mode mismatch(es), "
                f"{len(missing)} missing file(s)"
            )
        ),
        details={
            "mismatches": mismatches,
            "missing": missing,
        },
    )


def unit_properties(unit: str) -> dict[str, str]:
    result = run_command(
        [
            "systemctl",
            "show",
            unit,
            "-p",
            "LoadState",
            "-p",
            "ActiveState",
            "-p",
            "SubState",
            "-p",
            "UnitFileState",
            "-p",
            "Result",
            "-p",
            "ExecMainStatus",
        ]
    )

    if result.code != 0:
        return {}

    properties: dict[str, str] = {}

    for line in result.stdout.splitlines():
        key, separator, value = line.partition("=")

        if separator:
            properties[key] = value

    return properties


def installed_unit_files() -> set[str]:
    result = run_command(
        [
            "systemctl",
            "list-unit-files",
            "--no-legend",
            "--no-pager",
        ]
    )

    if result.code != 0:
        return set()

    units: set[str] = set()

    for line in result.stdout.splitlines():
        parts = line.split()

        if parts:
            units.add(parts[0])

    return units


def check_template_units(
    units: object,
    *,
    name: str,
) -> Check:
    if not isinstance(units, list):
        return Check(
            name=name,
            status="FAILED",
            message="Template unit configuration is not a list",
            details={},
        )

    installed = installed_unit_files()
    missing = [
        str(unit)
        for unit in units
        if str(unit) not in installed
    ]

    return Check(
        name=name,
        status="OK" if not missing else "FAILED",
        message=(
            f"{len(units)} template unit(s) available"
            if not missing
            else f"{len(missing)} template unit(s) missing"
        ),
        details={"missing": missing},
    )


def check_owned_units(
    baseline: dict[str, Any],
) -> Check:
    units = baseline.get("local_units", [])

    if not isinstance(units, list):
        return Check(
            name="local_units",
            status="FAILED",
            message="owned_units is not a list",
            details={},
        )

    failed: list[dict[str, Any]] = []
    states: dict[str, dict[str, str]] = {}

    for raw_unit in units:
        unit = str(raw_unit)
        properties = unit_properties(unit)
        states[unit] = properties

        if properties.get("LoadState") != "loaded":
            failed.append(
                {
                    "unit": unit,
                    "reason": "not loaded",
                    "properties": properties,
                }
            )

    return Check(
        name="local_units",
        status="OK" if not failed else "FAILED",
        message=(
            f"{len(units)} owned unit(s) loaded"
            if not failed
            else f"{len(failed)} owned unit(s) unavailable"
        ),
        details={
            "failed": failed,
            "states": states,
        },
    )


def check_external_integrations(
    baseline: dict[str, Any],
) -> Check:
    integrations = baseline.get(
        "external_integrations",
        {},
    )

    if not isinstance(integrations, dict):
        return Check(
            name="external_integrations",
            status="FAILED",
            message=(
                "external_integrations is not an object"
            ),
            details={},
        )

    failures: list[dict[str, str]] = []
    checked = 0

    for name, raw_config in integrations.items():
        if not isinstance(raw_config, dict):
            failures.append(
                {
                    "integration": str(name),
                    "reason": "invalid configuration",
                }
            )
            continue

        root = Path(str(raw_config.get("root", "")))

        if not root.is_dir():
            failures.append(
                {
                    "integration": str(name),
                    "reason": f"missing root: {root}",
                }
            )

        units = raw_config.get("units", [])

        if not isinstance(units, list):
            failures.append(
                {
                    "integration": str(name),
                    "reason": "units is not a list",
                }
            )
            continue

        for raw_unit in units:
            unit = str(raw_unit)
            checked += 1
            properties = unit_properties(unit)

            if properties.get("LoadState") != "loaded":
                failures.append(
                    {
                        "integration": str(name),
                        "reason": f"unit not loaded: {unit}",
                    }
                )

        template_units = raw_config.get(
            "template_units",
            [],
        )

        if not isinstance(template_units, list):
            failures.append(
                {
                    "integration": str(name),
                    "reason": "template_units is not a list",
                }
            )
            continue

        installed = installed_unit_files()

        for raw_unit in template_units:
            unit = str(raw_unit)
            checked += 1

            if unit not in installed:
                failures.append(
                    {
                        "integration": str(name),
                        "reason": (
                            f"template unit not installed: {unit}"
                        ),
                    }
                )

    return Check(
        name="external_integrations",
        status="OK" if not failures else "WARNING",
        message=(
            f"{checked} external unit(s) available"
            if not failures
            else (
                f"{len(failures)} external integration "
                "warning(s)"
            )
        ),
        details={"failures": failures},
    )


def check_runtime_root(
    baseline: dict[str, Any],
) -> Check:
    path = Path(
        str(
            baseline.get(
                "runtime_root",
                "/var/lib/5ibr-infra",
            )
        )
    )

    exists = path.is_dir()

    return Check(
        name="runtime_root",
        status="OK" if exists else "FAILED",
        message=(
            f"Runtime root available: {path}"
            if exists
            else f"Runtime root missing: {path}"
        ),
        details={"path": str(path)},
    )


def check_health() -> Check:
    result = run_command(
        [
            str(HEALTHCHECK_PATH),
            "--json",
        ],
        timeout=90,
        cwd=PROJECT_ROOT,
    )

    try:
        data = json.loads(result.stdout)
    except json.JSONDecodeError:
        return Check(
            name="health",
            status="FAILED",
            message=(
                result.stderr
                or "Health check returned invalid JSON"
            ),
            details={
                "exit_code": result.code,
                "stdout": result.stdout[:1000],
            },
        )

    if not isinstance(data, dict):
        return Check(
            name="health",
            status="FAILED",
            message="Health check returned invalid structure",
            details={"exit_code": result.code},
        )

    overall = str(
        data.get("overall_status", "FAILED")
    )

    return Check(
        name="health",
        status=(
            "OK"
            if result.code == 0
            and overall == "HEALTHY"
            else "FAILED"
        ),
        message=f"overall_status={overall}",
        details={
            "exit_code": result.code,
            "summary": data.get("summary"),
        },
    )


def build_doctor_report() -> dict[str, Any]:
    baseline_check = check_baseline()
    checks: list[Check] = [
        baseline_check,
        check_version(),
        (
            check_package_state()
            if PACKAGE_MODE
            else check_git_state()
        ),
    ]

    baseline: dict[str, Any] = {}

    if baseline_check.status == "OK":
        baseline = load_json_object(BASELINE_PATH)

        checks.extend(
            [
                *(
                    []
                    if PACKAGE_MODE
                    else [
                        check_tracked_permissions(
                            baseline
                        )
                    ]
                ),
                check_owned_units(baseline),
                check_template_units(
                    baseline.get("local_template_units", []),
                    name="local_template_units",
                ),
                check_external_integrations(baseline),
                check_runtime_root(baseline),
            ]
        )

    if os.geteuid() == 0:
        checks.append(check_health())
    else:
        checks.append(
            Check(
                name="health",
                status="WARNING",
                message=(
                    "Run as root to execute the full health check"
                ),
                details={"effective_uid": os.geteuid()},
            )
        )

    failed = sum(
        check.status == "FAILED"
        for check in checks
    )
    warnings = sum(
        check.status == "WARNING"
        for check in checks
    )
    ok = sum(
        check.status == "OK"
        for check in checks
    )

    if failed:
        decision = "NOT PRODUCTION READY"
    elif warnings:
        decision = "PRODUCTION READY WITH WARNINGS"
    else:
        decision = "PRODUCTION READY"

    return {
        "schema_version": 1,
        "project": "5ibr Infrastructure",
        "version": (
            VERSION_PATH.read_text(
                encoding="utf-8"
            ).strip()
            if VERSION_PATH.is_file()
            else None
        ),
        "decision": decision,
        "summary": {
            "total": len(checks),
            "ok": ok,
            "warnings": warnings,
            "failed": failed,
        },
        "checks": [
            asdict(check)
            for check in checks
        ],
    }


def print_report(report: dict[str, Any]) -> None:
    print("5ibr Infrastructure Doctor")
    print(f"Decision: {report['decision']}")

    summary = report["summary"]

    print(
        "Summary: "
        f"{summary['ok']} OK, "
        f"{summary['warnings']} WARNING, "
        f"{summary['failed']} FAILED"
    )
    print()

    for check in report["checks"]:
        print(
            f"[{check['status']}] "
            f"{check['name']}: "
            f"{check['message']}"
        )


def command_status() -> int:
    result = run_command(
        [str(STATUS_SCRIPT)],
        timeout=60,
        cwd=PROJECT_ROOT,
    )

    if result.stdout:
        print(result.stdout)

    if result.stderr:
        print(
            result.stderr,
            file=sys.stderr,
        )

    return result.code


def command_validate(json_output: bool) -> int:
    command = [str(HEALTHCHECK_PATH)]

    if json_output:
        command.append("--json")

    result = run_command(
        command,
        timeout=90,
        cwd=PROJECT_ROOT,
    )

    if result.stdout:
        print(result.stdout)

    if result.stderr:
        print(
            result.stderr,
            file=sys.stderr,
        )

    return result.code


def command_prune(dry_run: bool) -> int:
    command = [
        sys.executable,
        str(PRUNE_SCRIPT),
    ]

    if dry_run:
        command.append("--dry-run")

    result = run_command(
        command,
        timeout=120,
        cwd=PROJECT_ROOT,
    )

    if result.stdout:
        print(result.stdout)

    if result.stderr:
        print(
            result.stderr,
            file=sys.stderr,
        )

    return result.code


def command_doctor(json_output: bool) -> int:
    report = build_doctor_report()

    if json_output:
        print(
            json.dumps(
                report,
                ensure_ascii=False,
                indent=2,
            )
        )
    else:
        print_report(report)

    return (
        1
        if report["decision"]
        == "NOT PRODUCTION READY"
        else 0
    )


def command_release_check(
    json_output: bool,
) -> int:
    report = build_doctor_report()

    if report["decision"] != "PRODUCTION READY":
        if json_output:
            print(
                json.dumps(
                    report,
                    ensure_ascii=False,
                    indent=2,
                )
            )
        else:
            print_report(report)

        return 1

    report["release_check"] = {
        "status": "PASSED",
        "message": (
            "Production baseline checks passed"
        ),
    }

    if json_output:
        print(
            json.dumps(
                report,
                ensure_ascii=False,
                indent=2,
            )
        )
    else:
        print_report(report)
        print()
        print("Release check: PASSED")

    return 0


def command_fleet_passthrough(
    command: str,
    arguments: Sequence[str],
) -> int:
    if not FLEET_CLI_PATH.is_file():
        print(
            f"Fleet CLI not found: {FLEET_CLI_PATH}",
            file=sys.stderr,
        )
        return 1

    result = run_command(
        [
            sys.executable,
            str(FLEET_CLI_PATH),
            command,
            *arguments,
        ],
        timeout=120,
        cwd=PROJECT_ROOT,
    )

    if result.stdout:
        print(result.stdout)

    if result.stderr:
        print(
            result.stderr,
            file=sys.stderr,
        )

    return result.code


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        prog="5ibr-infra",
        description=(
            "Unified operations interface for "
            "5ibr Infrastructure."
        ),
    )

    parser.add_argument(
        "--json",
        action="store_true",
        help="Emit structured JSON when supported.",
    )

    subparsers = parser.add_subparsers(
        dest="command",
        required=True,
    )

    subparsers.add_parser(
        "status",
        help="Show current infrastructure status.",
    )

    subparsers.add_parser(
        "validate",
        help="Run the infrastructure health check.",
    )

    subparsers.add_parser(
        "doctor",
        help="Evaluate production readiness.",
    )

    prune_parser = subparsers.add_parser(
        "prune",
        help="Prune runtime history safely.",
    )
    prune_parser.add_argument(
        "--dry-run",
        action="store_true",
        help="Report pruning without modifying files.",
    )

    subparsers.add_parser(
        "release-check",
        help="Require a clean production-ready baseline.",
    )

    node_parser = subparsers.add_parser(
        "node",
        help="Inspect inventory nodes.",
    )
    node_parser.add_argument(
        "fleet_arguments",
        nargs=argparse.REMAINDER,
        help="Arguments passed to the fleet node interface.",
    )

    fleet_parser = subparsers.add_parser(
        "fleet",
        help="Inspect the infrastructure fleet.",
    )
    fleet_parser.add_argument(
        "fleet_arguments",
        nargs=argparse.REMAINDER,
        help="Arguments passed to the fleet interface.",
    )

    return parser.parse_args()


def main() -> int:
    args = parse_args()

    if args.command == "status":
        return command_status()

    if args.command == "validate":
        return command_validate(args.json)

    if args.command == "doctor":
        return command_doctor(args.json)

    if args.command == "prune":
        return command_prune(args.dry_run)

    if args.command == "release-check":
        return command_release_check(args.json)

    if args.command in {"node", "fleet"}:
        return command_fleet_passthrough(
            args.command,
            args.fleet_arguments,
        )

    raise RuntimeError(
        f"Unsupported command: {args.command}"
    )


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