"""CLI command for deploy."""

from __future__ import annotations

from pathlib import Path

import click

from kuberoku.cli.context import resolve_app
from kuberoku.cli.output import hint, info, render_detail, success
from kuberoku.sdk.deploy import parse_port


@click.command("deploy")
@click.option("--app", "-a", "app_flag", default=None, help="Target app.")
@click.option("--image", default=None, help="Pre-built image to deploy.")
@click.option("--ref", default=None, help="Git ref to build (default: HEAD).")
@click.option("--type", "process_type", default=None, help="Only update this process type.")
@click.option(
    "--port",
    "port_specs",
    multiple=True,
    help="Port/protocol (e.g., 8080/tcp). Repeatable.",
)
@click.option("--replicas", default=1, type=int, help="Initial replica count (first deploy only).")
@click.option("--wait/--no-wait", default=True, help="Wait for rollout (default: --wait).")
@click.option("--timeout", default=300, type=int, help="Rollout timeout in seconds.")
@click.option("--no-procfile", is_flag=True, help="Skip Procfile reading.")
@click.pass_context
def deploy(
    ctx: click.Context,
    app_flag: str | None,
    image: str | None,
    ref: str | None,
    process_type: str | None,
    port_specs: tuple[str, ...],
    replicas: int,
    wait: bool,
    timeout: int,
    no_procfile: bool,
) -> None:
    """Deploy an application."""
    app_name = resolve_app(app_flag)
    factory = ctx.obj["factory"]

    # Parse port specs
    ports = None
    if port_specs:
        ports = [parse_port(p) for p in port_specs]

    # Resolve Procfile path
    procfile_path: Path | None = None
    if not no_procfile:
        procfile_path = Path("Procfile")

    release = factory.deploy.deploy(
        app_name,
        image=image,
        ref=ref,
        process_type=process_type,
        ports=ports,
        replicas=replicas,
        procfile_path=procfile_path,
        no_procfile=no_procfile,
        wait=wait,
        timeout=timeout,
        on_step=lambda msg: info(msg),
    )

    success(f"Release v{release.version} created.")
    render_detail(
        f"{app_name} v{release.version}",
        {
            "Image": next(iter(release.images.values()), ""),
            "Processes": ", ".join(release.images.keys()),
        },
    )
    hint("\nNext steps:")
    hint(f"  kuberoku services:connect --app {app_name}         # access locally")
    hint(f"  kuberoku services:expose:on --app {app_name} web   # expose to internet")
    hint(f"  kuberoku services:logs --app {app_name} --tail")
