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

import json

import boto3
import typer

from .ami import build_report as build_ami_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("ami")
def ami_report(
    orphaned: bool = typer.Option(False, "--orphaned", help="Show only orphaned AMIs"),
    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."""
    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}  {'Snaps':>5}  References"
        )
        typer.echo(
            f"{'-' * name_width}  {'-' * 21}  {'-' * 12}  {'-' * 5}  {'-' * 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 = "-"
            snap_count = len(r.snapshot_ids)
            typer.echo(
                f"{r.name:<{name_width}}  {r.id:<21}  {created_str:<12}  {r.instance_count:>5}  {snap_count:>5}  {refs_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 if r.is_orphaned)
        typer.echo()
        typer.echo(
            f"Total: {len(report)} AMIs, {orphaned_count} orphaned ({total_snapshots} snapshots)"
        )
