#!/usr/bin/env python3

from __future__ import annotations

import argparse
import os
import re
import subprocess
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import 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"}
)

VERSION_PATH = PROJECT_ROOT / "VERSION"
INSTALLER_PATH = (
    PROJECT_ROOT
    / "scripts"
    / "install"
    / "5ibr-infra-install"
)
INSTALLED_VERSION_PATH = Path(
    "/var/lib/5ibr-infra/installed-version"
)

VERSION_PATTERN = re.compile(
    r"^[0-9]+\.[0-9]+\.[0-9]+$"
)


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


def run(
    command: Sequence[str],
    *,
    timeout: int = 300,
) -> CommandResult:
    try:
        completed = subprocess.run(
            list(command),
            check=False,
            capture_output=True,
            text=True,
            timeout=timeout,
        )
    except subprocess.TimeoutExpired as exc:
        return CommandResult(
            code=124,
            stdout=(
                exc.stdout
                if isinstance(exc.stdout, str)
                else ""
            ),
            stderr=(
                exc.stderr
                if isinstance(exc.stderr, str)
                else f"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 require_root() -> None:
    if os.geteuid() != 0:
        raise SystemExit(
            "This upgrade tool must run as root."
        )


def parse_version(value: str) -> tuple[int, int, int]:
    value = value.strip()

    if not VERSION_PATTERN.fullmatch(value):
        raise ValueError(
            f"Invalid semantic version: {value!r}"
        )

    major, minor, patch = value.split(".")

    return (
        int(major),
        int(minor),
        int(patch),
    )


def read_target_version() -> str:
    if not VERSION_PATH.is_file():
        raise SystemExit(
            f"Missing target VERSION file: {VERSION_PATH}"
        )

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

    try:
        parse_version(version)
    except ValueError as exc:
        raise SystemExit(str(exc)) from exc

    return version


def read_installed_version() -> str | None:
    if not INSTALLED_VERSION_PATH.is_file():
        return None

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

    try:
        parse_version(version)
    except ValueError as exc:
        raise SystemExit(
            f"Invalid installed version state: {exc}"
        ) from exc

    return version


def compare_versions(
    installed: str | None,
    target: str,
) -> str:
    if installed is None:
        return "fresh"

    installed_value = parse_version(installed)
    target_value = parse_version(target)

    if target_value < installed_value:
        return "downgrade"

    if target_value == installed_value:
        return "same"

    return "upgrade"


def run_installer(dry_run: bool) -> None:
    command = [str(INSTALLER_PATH)]

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

    result = run(
        command,
        timeout=600,
    )

    if result.stdout:
        print(result.stdout)

    if result.code != 0:
        raise SystemExit(
            result.stderr
            or "Installer execution failed"
        )


def write_installed_version(version: str) -> None:
    INSTALLED_VERSION_PATH.parent.mkdir(
        parents=True,
        mode=0o700,
        exist_ok=True,
    )

    temporary = INSTALLED_VERSION_PATH.with_name(
        INSTALLED_VERSION_PATH.name + ".tmp"
    )

    temporary.write_text(
        version + "\n",
        encoding="utf-8",
    )
    temporary.chmod(0o600)

    if os.geteuid() == 0:
        os.chown(temporary, 0, 0)

    temporary.replace(
        INSTALLED_VERSION_PATH
    )


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        prog="5ibr-infra-upgrade",
        description=(
            "Upgrade the 5ibr Infrastructure installation "
            "safely."
        ),
    )
    parser.add_argument(
        "--dry-run",
        action="store_true",
        help=(
            "Validate the upgrade without modifying "
            "installed files or version state."
        ),
    )
    parser.add_argument(
        "--allow-same-version",
        action="store_true",
        help=(
            "Allow reinstalling the currently installed "
            "version."
        ),
    )
    parser.add_argument(
        "--allow-downgrade",
        action="store_true",
        help=(
            "Explicitly permit installing an older version."
        ),
    )

    return parser.parse_args()


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

    require_root()

    target = read_target_version()
    installed = read_installed_version()
    action = compare_versions(
        installed,
        target,
    )

    print(
        "Installed version:",
        installed or "not recorded",
    )
    print("Target version:", target)
    print("Upgrade action:", action)

    if action == "same" and not args.allow_same_version:
        raise SystemExit(
            "Target version is already installed. "
            "Use --allow-same-version to reinstall."
        )

    if action == "downgrade" and not args.allow_downgrade:
        raise SystemExit(
            "Downgrade blocked. "
            "Use --allow-downgrade to proceed explicitly."
        )

    run_installer(args.dry_run)

    if args.dry_run:
        print("Upgrade dry-run: PASSED")
        return 0

    write_installed_version(target)

    print(
        f"5ibr Infrastructure version {target} "
        "installed successfully"
    )

    return 0


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