#!/usr/bin/env python3
import platform
import subprocess
import sys
from pathlib import Path

import click

OS = platform.system().lower()
SCRIPT_EXT = ".ps1" if OS == "windows" else ".sh"
SCRIPT_DIR = "Windows" if OS == "windows" else "Unix"
PROJECT_ROOT = Path(__file__).parent.absolute()
SCRIPTS_PATH = PROJECT_ROOT / "scripts" / SCRIPT_DIR


def get_script_path(command: str) -> Path:
    return SCRIPTS_PATH / f"{command}{SCRIPT_EXT}"


def run_script(script_name: str, *args) -> int:
    script_path = get_script_path(script_name)

    if not script_path.exists():
        click.secho(
            f"Error: Script '{script_name}' not found at {script_path}",
            fg="red",
            err=True,
        )
        return 1

    if OS == "windows":
        cmd = ["pwsh", "-File", str(script_path)]
    else:
        cmd = ["bash", str(script_path)]

    cmd.extend(args)

    try:
        result = subprocess.run(cmd, cwd=PROJECT_ROOT)
        return result.returncode
    except FileNotFoundError:
        shell_name = "PowerShell" if OS == "windows" else "bash"
        click.secho(
            f"Error: {shell_name} not found. Please ensure it's installed.",
            fg="red",
            err=True,
        )
        return 127
    except KeyboardInterrupt:
        click.secho("\nOperation cancelled by user.", fg="yellow")
        return 130


@click.group(
    context_settings={"help_option_names": ["-h", "--help"]},
    invoke_without_command=True,
)
@click.pass_context
def cli(ctx):
    if ctx.invoked_subcommand is None:
        click.echo(ctx.get_help())


@cli.command()
def install():
    return sys.exit(run_script("install"))


@cli.command()
def run():
    return sys.exit(run_script("run"))


@cli.command()
def restart():
    return sys.exit(run_script("restart"))


@cli.command()
@click.option(
    "-r",
    "--report",
    type=click.Choice(["xml", "html"]),
    help="Generate coverage report (xml or html)",
)
def test(report):
    args = []
    if report:
        args.extend(["-r", report])
    return sys.exit(run_script("test", *args))


@cli.command()
def uninstall():
    if click.confirm(
        "This will remove all Docker containers, volumes, and generated files. Continue?"
    ):
        return sys.exit(run_script("uninstall"))
    else:
        click.secho("Uninstall cancelled.", fg="yellow")
        return 0


@cli.command()
def backup():
    return sys.exit(run_script("backup"))


@cli.command(name="generate-env")
def generate_env():
    return sys.exit(run_script("generate-environment-file"))


@cli.command(name="export-env")
def export_env():
    return sys.exit(run_script("export-environment-file"))


@cli.command(name="make-messages")
def make_messages():
    return sys.exit(run_script("make-messages"))


@cli.command(name="compile-messages")
def compile_messages():
    return sys.exit(run_script("compile-messages"))


@cli.command()
def info():
    click.echo(f"{'=' * 60}")
    click.secho("lessy - eVibes Project CLI", fg="cyan", bold=True)
    click.echo(f"{'=' * 60}")
    click.echo(f"Operating System: {platform.system()} ({platform.release()})")
    click.echo(f"Python Version: {platform.python_version()}")
    click.echo(f"Architecture: {platform.machine()}")
    click.echo(f"Project Root: {PROJECT_ROOT}")
    click.echo(f"Scripts Directory: {SCRIPTS_PATH}")
    click.echo(f"Script Extension: {SCRIPT_EXT}")
    click.echo(f"{'=' * 60}")


if __name__ == "__main__":
    cli()
