"""alice run — Pass-through to the AWS CLI with ALICE defaults injected."""

from __future__ import annotations

import subprocess
import sys
from typing import TYPE_CHECKING

import click

from alice_cli.validators import check_aws_cli

if TYPE_CHECKING:
    from alice_cli.models import CLIConfig


def build_aws_command(args: tuple[str, ...] | list[str], config: CLIConfig) -> list[str]:
    """Build the full AWS CLI command with injected --region and --profile.

    Injects ``--region`` from config if not already present in *args*.
    Injects ``--profile`` from config if not already present and config.profile is set.

    Returns the complete command list starting with ``aws``.
    """
    cmd: list[str] = list(args)

    if "--region" not in cmd:
        cmd = ["--region", config.region] + cmd

    if "--profile" not in cmd and config.profile is not None:
        cmd = ["--profile", config.profile] + cmd

    return ["aws"] + cmd


@click.command("run", context_settings={"ignore_unknown_options": True})
@click.argument("args", nargs=-1, type=click.UNPROCESSED)
@click.pass_context
def run_cmd(ctx: click.Context, args: tuple[str, ...]) -> None:
    """Run AWS CLI commands with alice defaults."""
    config: CLIConfig = ctx.obj["config"]

    check_aws_cli()

    cmd = build_aws_command(args, config)
    result = subprocess.run(cmd)
    sys.exit(result.returncode)
