"""CLI commands for resource lookup."""

import json

import boto3
import typer

from .ami import build_report as build_ami_report
from .ami import delete_ami
from .lc import build_report as build_lc_report
from .lt import build_report as build_lt_report

app = typer.Typer(help="Resource lookup tools")


@app.command("lt")
def lt_report(
    orphaned: bool = typer.Option(
        False, "--orphaned", help="Show only orphaned launch templates"
    ),
    sort: str = typer.Option("name", "-s", "--sort", help="Sort by: name, created"),
    json_output: bool = typer.Option(False, "--json", help="Output as JSON"),
    region: str = typer.Option(None, "-r", "--region", help="AWS region"),
):
    """Launch Template usage report."""
    session = boto3.Session(region_name=region)
    report = build_lt_report(session)

    # Sort
    if sort == "name":
        report.sort(key=lambda r: r.name)
    elif sort == "created":
        report.sort(key=lambda r: r.created)
    else:
        typer.echo(f"Unknown sort column: {sort}. Use 'name' or 'created'.")
        raise typer.Exit(1)

    if orphaned:
        report = [r for r in report if r.is_orphaned]

    if json_output:
        print(json.dumps([r.to_dict() for r in report], indent=2))
    else:
        if not report:
            typer.echo("No launch templates found.")
            return

        # Calculate column widths
        name_width = max(len(r.name) for r in report)
        name_width = max(name_width, len("Launch Template"))

        # Header
        typer.echo(
            f"{'Launch Template':<{name_width}}  {'Created':<12}  {'EC2':>5}  References"
        )
        typer.echo(f"{'-' * name_width}  {'-' * 12}  {'-' * 5}  {'-' * 40}")

        # Rows
        for r in report:
            created_str = r.created.strftime("%Y-%m-%d")
            if r.references:
                refs_str = ", ".join(f"{ref.type}:{ref.name}" for ref in r.references)
            else:
                refs_str = "-"
            typer.echo(
                f"{r.name:<{name_width}}  {created_str:<12}  {r.instance_count:>5}  {refs_str}"
            )

        # Summary
        orphaned_count = sum(1 for r in report if r.is_orphaned)
        typer.echo()
        typer.echo(f"Total: {len(report)} launch templates, {orphaned_count} orphaned")


@app.command("lc")
def lc_report(
    orphaned: bool = typer.Option(
        False, "--orphaned", help="Show only orphaned launch configurations"
    ),
    sort: str = typer.Option("name", "-s", "--sort", help="Sort by: name, created"),
    json_output: bool = typer.Option(False, "--json", help="Output as JSON"),
    region: str = typer.Option(None, "-r", "--region", help="AWS region"),
):
    """Launch Configuration usage report."""
    session = boto3.Session(region_name=region)
    report = build_lc_report(session)

    # Sort
    if sort == "name":
        report.sort(key=lambda r: r.name)
    elif sort == "created":
        report.sort(key=lambda r: r.created)
    else:
        typer.echo(f"Unknown sort column: {sort}. Use 'name' or 'created'.")
        raise typer.Exit(1)

    if orphaned:
        report = [r for r in report if r.is_orphaned]

    if json_output:
        print(json.dumps([r.to_dict() for r in report], indent=2))
    else:
        if not report:
            typer.echo("No launch configurations found.")
            return

        # Calculate column widths
        name_width = max(len(r.name) for r in report)
        name_width = max(name_width, len("Launch Configuration"))

        # Header
        typer.echo(
            f"{'Launch Configuration':<{name_width}}  {'Created':<12}  {'AMI ID':<21}  References"
        )
        typer.echo(f"{'-' * name_width}  {'-' * 12}  {'-' * 21}  {'-' * 40}")

        # Rows
        for r in report:
            created_str = r.created.strftime("%Y-%m-%d")
            refs_str = (
                ", ".join(f"{ref.type}:{ref.name}" for ref in r.references)
                if r.references
                else "-"
            )
            typer.echo(
                f"{r.name:<{name_width}}  {created_str:<12}  {r.ami_id:<21}  {refs_str}"
            )

        # Summary
        orphaned_count = sum(1 for r in report if r.is_orphaned)
        typer.echo()
        typer.echo(
            f"Total: {len(report)} launch configurations, {orphaned_count} orphaned"
        )


@app.command("ami")
def ami_report(
    orphaned: bool = typer.Option(False, "--orphaned", help="Show only orphaned AMIs"),
    delete: bool = typer.Option(
        False, "--delete", help="Interactive deletion (requires --orphaned)"
    ),
    sort: str = typer.Option("name", "-s", "--sort", help="Sort by: name, created"),
    json_output: bool = typer.Option(False, "--json", help="Output as JSON"),
    region: str = typer.Option(None, "-r", "--region", help="AWS region"),
):
    """AMI usage report."""
    if delete and not orphaned:
        typer.echo("--delete requires --orphaned")
        raise typer.Exit(1)

    session = boto3.Session(region_name=region)
    report = build_ami_report(session)

    # Sort
    if sort == "name":
        report.sort(key=lambda r: r.name)
    elif sort == "created":
        report.sort(key=lambda r: r.created)
    else:
        typer.echo(f"Unknown sort column: {sort}. Use 'name' or 'created'.")
        raise typer.Exit(1)

    if orphaned:
        report = [r for r in report if r.is_orphaned]

    if json_output:
        print(json.dumps([r.to_dict() for r in report], indent=2))
    else:
        if not report:
            typer.echo("No AMIs found.")
            return

        # Calculate column widths
        name_width = max(len(r.name) for r in report)
        name_width = max(name_width, len("AMI Name"))

        # Header
        typer.echo(
            f"{'AMI Name':<{name_width}}  {'AMI ID':<21}  {'Created':<12}  {'EC2':>5}  References  Snapshots"
        )
        typer.echo(f"{'-' * name_width}  {'-' * 21}  {'-' * 12}  {'-' * 5}  {'-' * 40}")

        # Rows
        for r in report:
            created_str = r.created.strftime("%Y-%m-%d")
            refs_str = (
                ", ".join(f"{ref.type}:{ref.name}" for ref in r.references)
                if r.references
                else "-"
            )
            snaps_str = ", ".join(r.snapshot_ids) if r.snapshot_ids else "-"
            typer.echo(
                f"{r.name:<{name_width}}  {r.id:<21}  {created_str:<12}  {r.instance_count:>5}  {refs_str}  {snaps_str}"
            )

        # Summary
        orphaned_count = sum(1 for r in report if r.is_orphaned)
        total_snapshots = sum(len(r.snapshot_ids) for r in report)
        typer.echo()
        typer.echo(
            f"Total: {len(report)} AMIs ({total_snapshots} snapshots), {orphaned_count} orphaned"
        )

        # Interactive deletion
        if delete and report:
            typer.echo()
            typer.echo("Starting interactive deletion (y=delete, n=skip, q=quit)")
            typer.echo()

            deleted_amis = 0
            deleted_snaps = 0

            for r in report:
                created_str = r.created.strftime("%Y-%m-%d")
                total_size = sum(s.size_gb for s in r.snapshots)
                typer.echo(f"AMI: {r.name}")
                typer.echo(f"  ID:      {r.id}")
                typer.echo(f"  Created: {created_str}")
                if r.snapshots:
                    typer.echo(f"  Snapshots ({len(r.snapshots)}, {total_size} GB):")
                    for snap in r.snapshots:
                        typer.echo(f"    - {snap.id} ({snap.size_gb} GB)")
                else:
                    typer.echo("  Snapshots: none")

                while True:
                    choice = typer.prompt("Delete?", default="y")
                    if choice.lower() == "y":
                        delete_ami(session, r.id, r.snapshot_ids)
                        deleted_amis += 1
                        deleted_snaps += len(r.snapshot_ids)
                        break
                    elif choice.lower() == "n":
                        typer.echo("  Skipped")
                        break
                    elif choice.lower() == "q":
                        typer.echo()
                        typer.echo(
                            f"Deleted {deleted_amis} AMIs, {deleted_snaps} snapshots"
                        )
                        return
                    else:
                        typer.echo("  Invalid choice. Use y/n/q")

                typer.echo()

            typer.echo(f"Deleted {deleted_amis} AMIs, {deleted_snaps} snapshots")
