#!/usr/bin/env python3

import argparse
from pathlib import Path
from typing import Literal

from lib.logging import LOGGER, DiskoMessage, debug, info
from lib.result import DiskoError, DiskoSuccess, DiskoResult, exit_on_error

Mode = Literal[
    "destroy", "format", "mount", "destroy,format,mount", "format,mount", "generate"
]


# Modes to apply an existing configuration
APPLY_MODES: list[Mode] = [
    "destroy",
    "format",
    "mount",
    "destroy,format,mount",
    "format,mount",
]
ALL_MODES: list[Mode] = APPLY_MODES + ["generate"]

MODE_DESCRIPTION: dict[Mode, str] = {
    "destroy": "Destroy the partition tables on the specified disks",
    "format": "Change formatting and filesystems on the specified disks",
    "mount": "Mount the specified disks",
    "destroy,format,mount": "Run destroy, format and mount in sequence",
    "format,mount": "Run format and mount in sequence",
    "generate": "Generate a disko configuration file from the system's current state",
}


def run_apply(*, mode: str, disko_file: Path | None, flake: str | None) -> DiskoResult:
    if flake is None and disko_file is None:
        return DiskoError([DiskoMessage("ERR_MISSING_ARGUMENTS")], "validate args")
    if flake is not None and disko_file is not None:
        return DiskoError([DiskoMessage("ERR_TOO_MANY_ARGUMENTS")], "validate args")

    return DiskoSuccess(
        {
            "mode": mode,
            "disko_file": disko_file,
            "flake": flake,
        },
        "apply configuration",
    )


def run_generate() -> DiskoResult:
    return DiskoSuccess("generate", "generate config")


def run(args: argparse.Namespace) -> DiskoResult:
    if args.verbose == True:
        LOGGER.setLevel("DEBUG")
        debug("Enabled debug logging.")

    if args.mode == None:
        return DiskoError(
            [DiskoMessage("ERR_MISSING_MODE", {"valid_modes": ALL_MODES})],
            "select mode",
        )

    if args.mode == "generate":
        return run_generate()

    return run_apply(**vars(args))


def parse_args() -> argparse.Namespace:
    root_parser = argparse.ArgumentParser(
        prog="disko2",
        description="Automated disk partitioning and formatting tool for NixOS",
    )

    root_parser.add_argument(
        "--verbose",
        "-v",
        action="store_true",
        default=False,
        help="Print more detailed output, helpful for debugging",
    )

    mode_parsers = root_parser.add_subparsers(dest="mode")

    def create_apply_parser(mode: Mode) -> argparse.ArgumentParser:
        parser = mode_parsers.add_parser(
            mode,
            help=MODE_DESCRIPTION[mode],
        )
        parser.add_argument(
            "disko_file",
            nargs="?",
            default=None,
            help="Path to the disko configuration file",
        )
        parser.add_argument(
            "--flake",
            "-f",
            help="Flake to fetch the disko configuration from",
        )
        return parser

    # Commands to apply an existing configuration
    apply_parsers = [create_apply_parser(mode) for mode in APPLY_MODES]

    # Other commands
    generate_parser = mode_parsers.add_parser(
        "generate",
        help=MODE_DESCRIPTION["generate"],
    )
    return root_parser.parse_args()


def main() -> None:
    args = parse_args()
    result = run(args)
    output = exit_on_error(result)
    info(str(output))


if __name__ == "__main__":
    main()
