#! /usr/bin/python3

"""
offline-installer: Manage offline installation of Debian/Ubuntu packages.

This tool solves the problem of installing packages on machines that have no
internet access. It operates in two stages:

  Stage 1 — "get" (run on an internet-connected machine):
    Recursively resolves dependencies for the requested packages, downloads all
    required .deb files via apt-get, and bundles them into a single .tar.gz
    archive that can be transferred to the target machine.

  Stage 2 — "install" (run on the offline target machine):
    Unpacks the archive, registers its contents as a local APT repository, and
    uses apt install to perform the installation (so that APT handles ordering
    and configuration automatically).

Commands:
    offline-installer get <package1> [package2] [...] [--depth N]
    offline-installer install <path_to_tar_or_folder> [--dry-run] [-y]

Flags:
    --depth N     (get)     Recursion depth for dependency resolution.
                            0 = requested packages only, no dependencies.
                            Default: 10, which covers virtually all real-world trees.

    --dry-run     (install) Simulate the installation without making any changes.
                            APT resolves and prints what it would install, but no
                            packages are actually written to the system. Useful for
                            verifying that the archive contains everything needed
                            before committing to the install.

    -y / --yes    (install) Headless / non-interactive mode. Skips the y/n
                            confirmation prompt, so the command can run unattended
                            in scripts or CI pipelines.

Examples:
    offline-installer get monitorix nginx
    offline-installer get monitorix nginx htop --depth 2
    offline-installer install ./packages-offline.tar.gz
    offline-installer install ./packages-offline.tar.gz --dry-run
    offline-installer install ./packages-offline.tar.gz -y
"""

from __future__ import annotations

import os
import sys
import argparse
import tarfile
import shutil
import subprocess
from datetime import datetime

from utils.offline_installer.utils import (
    InstallStatus,
    get_dependencies_and_version_constraints,
    install_packages,
    resolve_version_constraints,
    add_offline_package_local_repo,
    download_multi_threaded,
    cleanup_local_repo,
)


def get_packages(packages: list[str], depth: int) -> None:
    """Resolve dependencies, download all .deb files, and pack them into a tar.gz archive.

    This is the "get" stage, intended to run on a machine with internet access.
    The resulting archive can be copied to an offline machine and installed with
    the "install" subcommand.

    Workflow:
      1. Create a staging directory under /tmp with two sub-folders:
           - root (main_pkg_dir): main requested packages
           - dependencies/:        all transitive dependencies
      2. Run `apt update` to ensure the package index is current.
      3. Recursively collect all transitive dependencies and their version
         constraints for every requested package.
      4. Resolve version constraints using the python-apt cache to pick the
         newest version of each dependency that satisfies all constraints.
      5. Download main packages and dependencies in parallel into their
         respective folders.
      6. Pack everything into <archive_name>.tar.gz in the current working
         directory and remove the temporary staging directory.

    The archive layout is:
        mikado-offline-packages/
        ├── *.deb               (main requested packages)
        └── dependencies/
            └── *.deb           (all transitive dependencies)

    Args:
        packages: List of apt package name strings to download (as given on
                  the command line).
        depth:    Maximum recursion depth for dependency traversal. A depth of
                  0 downloads only the listed packages with no dependencies;
                  the default of 10 covers virtually all real-world trees.
    """
    archive_name = "mikado-offline-packages" + datetime.now().strftime(
        "-%Y-%m-%d-%H%M%S"
    )

    current_dir = os.getcwd()
    download_dir = os.path.join("/tmp", archive_name)
    main_pkg_dir = download_dir
    deps_dir = os.path.join(download_dir, "dependencies")

    os.makedirs(main_pkg_dir, exist_ok=True)
    os.makedirs(deps_dir, exist_ok=True)

    print(f"[+] Download directory: {download_dir}")
    print(f"    Main packages: {main_pkg_dir}")
    print(f"    Dependencies: {deps_dir}")
    print("[+] Updating package lists...")

    subprocess.run("sudo apt update -qq", shell=True, check=True)

    print(
        f"[+] Building dependency tree for {len(packages)} package(s) (depth={depth})..."
    )

    main_packages: set[str] = set(packages)
    all_pkgs: set[str] = set()
    all_constraints: dict[str, set[str]] = dict()

    for pkg in packages:
        print(f"\n[+] Processing '{pkg}'...")
        pkg_deps, constraints = get_dependencies_and_version_constraints(
            pkg, max_depth=depth
        )
        all_pkgs |= pkg_deps

        for p, c in constraints.items():
            all_constraints.setdefault(p, set()).update(c)

    if not all_pkgs:
        print(f"[!] No valid packages found")
        sys.exit(1)

    print("[+] Resolving dependency version constraints.")

    _pin_resolved_dependencies(all_pkgs, all_constraints)

    dependencies = all_pkgs - main_packages
    print(
        f"\n[+] Found {len(main_packages)} main package(s) and {len(dependencies)} dependencies to download."
    )
    print(f"[+] Starting download...")

    downloaded = 0
    failed = 0
    failed_pkg_names = []
    fallback_pkg_names = []

    print(f"\n[+] Downloading {len(main_packages)} main package(s):")
    os.chdir(main_pkg_dir)

    d, f, faild_pn, fallback_pn = download_multi_threaded(main_packages, max_workers=4)
    downloaded += d
    failed += f
    failed_pkg_names += faild_pn
    fallback_pkg_names += fallback_pn

    if dependencies:
        print(f"\n[+] Downloading {len(dependencies)} dependencies...")
        os.chdir(deps_dir)

        d, f, faild_pn, fallback_pn = download_multi_threaded(
            dependencies, max_workers=8
        )
        downloaded += d
        failed += f
        failed_pkg_names += faild_pn
        fallback_pkg_names += fallback_pn
    else:
        print("\n[+] No dependencies to download.")

    os.chdir(os.path.dirname(download_dir))

    print(f"\n[+] Packing files into {archive_name}.tar.gz ...")
    tmp_path = f"{download_dir}.tar.gz"
    offline_package_path = os.path.join(current_dir, f"{archive_name}.tar.gz")

    with tarfile.open(tmp_path, "w:gz") as tar:
        tar.add(download_dir, arcname=os.path.basename(download_dir))
    shutil.move(tmp_path, offline_package_path)

    print(f"[+] Cleaning up temporary directory...")
    shutil.rmtree(download_dir)
    print(f"    ✓ Removed {download_dir}")

    print("\n==========================================================")
    if failed:
        print(f"[!] Failed to download {failed} packages:")
    else:
        print("✅ Download complete and packed!")
    print(f"\nArchive saved: {offline_package_path}")
    print(f"Main packages: {len(main_packages)}")
    print(f"  {', '.join(sorted(main_packages))}")
    print(f"Downloaded: {downloaded}")
    print(f"Failed or Fallback:     {failed}")
    if failed:
        for failed_pkg_name, fallback_pkg_name in zip(
            failed_pkg_names, fallback_pkg_names
        ):
            if fallback_pkg_name is None:
                print(f"    [!] Failed to download '{failed_pkg_name}'.")
            else:
                print(
                    f"    [!] The package '{failed_pkg_name}' has an unknown version locally."
                )
                print(
                    f"       |-> The latest available version '{fallback_pkg_name}' was downloaded instead."
                )
        print(
            f"\n    [!] Consider to add the failed packages manually to the .deb Archive at: {offline_package_path}"
        )
    print(f"\nStructure:")
    print(f"  {archive_name}/")
    print(f"  ├── *.deb (main packages)")
    print(f"  └── dependencies/")
    print(f"      └── *.deb (dependency packages)")
    print("\nTo install offline later, run:")
    print(f"   offline-installer install {offline_package_path}")
    print("==========================================================")


def _pin_resolved_dependencies(
    all_pkgs: set[str], all_constraints: dict[str, set[str]]
) -> None:
    """Add exact version pins for dependencies with collected constraints."""
    resolved_dependencies: dict[str, tuple[str, str]] = dict()
    for pkg_name, constraints in all_constraints.items():
        resolved_pkg, version = resolve_version_constraints(pkg_name, constraints)
        resolved_dependencies[pkg_name] = (resolved_pkg, version)

    for pkg, (resolved_pkg, version) in resolved_dependencies.items():
        all_pkgs.remove(pkg)
        all_pkgs.add(f"{resolved_pkg}={version}")


def install(path: str, dry_run: bool, headless_mode: bool) -> None:
    """Register a local APT repository from an archive and install its packages.

    This is the "install" stage, intended to run on the offline target machine.
    It delegates the heavy lifting to utils helpers:
      - add_offline_package_local_repo: unpacks the archive and registers it
        as an APT source so that `apt install` can resolve packages locally.
      - install_packages: runs `apt install` and verifies the result.
      - cleanup_local_repo: removes the temporary APT source entry after a
        successful installation.

    On failure the local repository is intentionally left registered so the
    user can inspect the state and retry without re-extracting the archive.

    Args:
        path:          Path to a .tar.gz archive or a directory containing
                       .deb files (as produced by the "get" subcommand).
        dry_run:       If True, apt runs with --dry-run and nothing is actually
                       installed. Useful for verifying the package set.
        headless_mode: If True, skip the interactive y/n confirmation prompt
                       before installation begins (e.g. for CI/scripted use).
    """
    main_packages, repo_dir, sources_list = add_offline_package_local_repo(path)

    install_status = install_packages(main_packages, repo_dir, dry_run, headless_mode)

    if install_status in {InstallStatus.SUCCEEDED, InstallStatus.SKIPPED}:
        cleanup_local_repo(sources_list)
        print("\n==========================================================")
        if install_status is InstallStatus.SKIPPED:
            print("Installation skipped.")
        elif dry_run:
            print("✅ Dry run successfully completed!")
        else:
            print("✅ Installation complete!")
        print("==========================================================")
    else:
        print("\n==========================================================")
        print("[!] Installation failed or incomplete.")
        print(f"[!] Local repository is still registered at: {sources_list}")
        print("[!] You can manually clean it up with:")
        print(f"    sudo rm {sources_list}")
        print(f"    rm -r /var/tmp/offline-installer")
        print(f"    sudo apt-get update")
        print("==========================================================")


def main() -> None:
    """Parse command-line arguments and dispatch to the appropriate subcommand.

    Subcommands:
      get      Download packages + dependencies and pack as a .tar.gz archive.
               Accepts one or more package names and an optional --depth flag.

      install  Register a local APT repo from a .tar.gz or folder and install.
               Accepts --dry-run (simulate only) and -y/--yes (headless mode).
    """
    parser = argparse.ArgumentParser(
        prog="offline-installer",
        description="Download and manage offline Debian/Ubuntu repositories.",
    )

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

    get_parser = subparsers.add_parser(
        "get", help="Download packages and dependencies, then pack as tar.gz"
    )
    get_parser.add_argument("packages", nargs="+", help="Package name(s) to download.")
    get_parser.add_argument(
        "--depth",
        type=int,
        default=10,
        help="Recursion depth for dependencies (default: 10, 0 = packages only).",
    )

    install_parser = subparsers.add_parser(
        "install", help="Register a local offline repo (folder or .tar.gz)"
    )
    install_parser.add_argument(
        "path", help="Path to .tar.gz archive or folder containing .deb packages."
    )

    install_parser.add_argument(
        "--dry-run", action="store_true", help="Run without making any changes"
    )

    install_parser.add_argument(
        "-y",
        "--yes",
        action="store_true",
        help="Run in headless mode (auto-confirm, no prompts)",
    )

    args = parser.parse_args()

    if args.command == "get":
        get_packages(args.packages, args.depth)
    elif args.command == "install":
        if args.dry_run:
            print("[+] --dry-run -> Run without making any changes")
        if args.yes:
            print("[+] -y -> Run in headless mode (auto-confirm, no prompts)")
        install(args.path, args.dry_run, args.yes)
    else:
        parser.print_help()


if __name__ == "__main__":
    main()
