"""
CLI entry point for dxlabs.
Defines the command structure and handles user interaction for asset management.
"""

import os

import click
from rich.console import Console
from rich.panel import Panel

from .config import load_config, save_config
from .core.env_manager import EnvManager

console = Console()


@click.group()
def main():
    """
    dxlabs: DX Labs CLI for project asset management.
    A tool to manage environment files and other project resources efficiently.
    """
    pass


@main.command()
@click.option(
    "--bucket", required=True, help="The AWS S3 bucket name to use for storage."
)
@click.option(
    "--project", required=True, help="A unique project name (used as a key prefix)."
)
@click.option(
    "--region",
    default="ap-northeast-1",
    help="The AWS region to use. Defaults to ap-northeast-1.",
)
@click.option(
    "--profile", default=None, help="The AWS profile name to use for credentials."
)
def init(bucket, project, region, profile):
    """
    Initialize dxlabs configuration for the current project.
    Saves settings to a local .dxlabs.json file.
    """
    save_config(bucket, project, region, profile)
    profile_display = profile if profile else "default/env-var"
    console.print(
        Panel(
            f"Configuration saved to [bold cyan].dxlabs.json[/bold cyan]\n"
            f"Bucket: [green]{bucket}[/green]\n"
            f"Project: [green]{project}[/green]\n"
            f"Region: [green]{region}[/green]\n"
            f"Profile: [green]{profile_display}[/green]",
            title="Success",
        )
    )


@main.group()
def env():
    """
    Manage project environment (.env) files.
    Sub-commands for pushing to and pulling from the cloud.
    """
    pass


@env.command(name="push")
@click.option(
    "--env",
    "env_name",
    default="development",
    help="The environment name (e.g., 'dev', 'prod').",
)
@click.option(
    "--file",
    default=".env",
    help="Path to the local file to upload. Defaults to '.env'.",
)
def env_push(env_name, file):
    """
    Upload a local .env file to S3.
    """
    config = load_config()
    if not config:
        console.print(
            "[red]Error: Project not initialized. Run 'dxlabs init' first.[/red]"
        )
        return

    if not os.path.exists(file):
        console.print(f"[red]Error: Local file '{file}' not found.[/red]")
        return

    manager = EnvManager(config)
    remote_key = manager.get_remote_key(env_name)

    console.print(
        f"Uploading [cyan]{file}[/cyan] to [bold]s3://{config.bucket}/{remote_key}[/bold]..."
    )
    if manager.push(file, env_name):
        console.print("[bold green]Successfully uploaded![/bold green]")
    else:
        console.print("[bold red]Upload failed.[/bold red]")


@env.command(name="pull")
@click.option(
    "--env",
    "env_name",
    default="development",
    help="The environment name to download from.",
)
@click.option(
    "--file", default=".env", help="The local destination path. Defaults to '.env'."
)
def env_pull(env_name, file):
    """
    Download a .env file from S3 to the local filesystem.
    """
    config = load_config()
    if not config:
        console.print(
            "[red]Error: Project not initialized. Run 'dxlabs init' first.[/red]"
        )
        return

    manager = EnvManager(config)
    remote_key = manager.get_remote_key(env_name)

    console.print(
        f"Downloading from [bold]s3://{config.bucket}/{remote_key}[/bold] to [cyan]{file}[/cyan]..."
    )
    if manager.pull(env_name, file):
        console.print("[bold green]Successfully downloaded![/bold green]")
    else:
        console.print("[bold red]Download failed.[/bold red]")


if __name__ == "__main__":
    main()
