from __future__ import annotations

from typing import Annotated

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

from awspipe.backend import BackendAdapter
from awspipe.engine import QueryEngine
from awspipe.paths import database_path
from awspipe.render import render_csv, render_json, render_table
from awspipe.repl import run_shell


app = typer.Typer(help="Query AWS resources with SQL using a DuckDB-backed cache.")
cache_app = typer.Typer(help="Manage the local DuckDB cache.")
console = Console()
app.add_typer(cache_app, name="cache")


def build_engine() -> QueryEngine:
    return QueryEngine(backend=BackendAdapter(database_path()))


def _render_output(output: str, result) -> None:
    if output == "json":
        render_json(console, result)
        return
    if output == "csv":
        render_csv(console, result)
        return
    render_table(console, result)


def _handle_error(exc: Exception) -> None:
    console.print(Panel.fit(str(exc), title="awspipe error", border_style="red"))
    raise typer.Exit(code=1) from exc


@app.command()
def query(
    sql: str,
    profile: Annotated[str | None, typer.Option("--profile", help="AWS CLI profile name.")] = None,
    region: Annotated[str | None, typer.Option("--region", help="AWS region override.")] = None,
    all_regions: Annotated[bool, typer.Option("--all", help="Query all enabled AWS regions for regional tables.")] = False,
    refresh: Annotated[bool, typer.Option("--refresh", help="Bypass cache TTL for referenced tables.")] = False,
    output: Annotated[str, typer.Option("--output", help="Output format: table, json, or csv.")] = "table",
) -> None:
    engine = build_engine()
    try:
        result = engine.query(sql, profile=profile, region=region, refresh=refresh, all_regions=all_regions)
    except Exception as exc:
        _handle_error(exc)
    _render_output(output, result)


@app.command()
def shell(
    profile: Annotated[str | None, typer.Option("--profile", help="AWS CLI profile name.")] = None,
    region: Annotated[str | None, typer.Option("--region", help="AWS region override.")] = None,
    all_regions: Annotated[bool, typer.Option("--all", help="Query all enabled AWS regions for regional tables.")] = False,
) -> None:
    engine = build_engine()
    try:
        run_shell(console, engine, profile=profile, region=region, all_regions=all_regions)
    except Exception as exc:
        _handle_error(exc)


@app.command()
def tables() -> None:
    engine = build_engine()
    for provider in engine.available_tables():
        console.print(f"{provider.name}\t{provider.scope}\t{provider.description}")


@app.command()
def inspect(table_name: str) -> None:
    engine = build_engine()
    try:
        provider, columns = engine.inspect_table(table_name)
    except Exception as exc:
        _handle_error(exc)
    console.print(f"{provider.name}: {provider.description}")
    for column in columns:
        console.print(f"  {column.column} ({column.type_name}) - {column.description}")


@app.command()
def doctor(
    profile: Annotated[str | None, typer.Option("--profile", help="AWS CLI profile name.")] = None,
    region: Annotated[str | None, typer.Option("--region", help="AWS region override.")] = None,
) -> None:
    engine = build_engine()
    try:
        status = engine.doctor(profile=profile, region=region)
    except Exception as exc:
        _handle_error(exc)
    console.print(f"profile: {status.profile or 'default'}")
    console.print(f"region: {status.region}")
    console.print(f"account_id: {status.account_id}")
    console.print(f"arn: {status.arn}")
    console.print(f"cache_path: {status.cache_path}")


@cache_app.command("clear")
def cache_clear() -> None:
    engine = build_engine()
    engine.backend.clear_cache()
    console.print("Cache cleared.")
