#!/usr/bin/env python3
"""Persona-specific inventory reports for CTO, CFO, CloudOps, FinOps."""

from typing import Any

from rich.console import Console
from rich.panel import Panel
from rich.table import Table

PERSONA_CONFIGS: dict[str, dict[str, Any]] = {
    "cto": {
        "title": "CTO Infrastructure Overview",
        "columns": ["Resource Type", "Account", "Region", "VPC", "Tags"],
        "keys": ["resource_type", "account_name", "region", "vpc_id", "tags"],
    },
    "cfo": {
        "title": "CFO Cost Summary",
        "columns": ["Resource Type", "Account", "Monthly Cost", "Utilization"],
        "keys": ["resource_type", "account_id", "monthly_cost", "utilization_pct"],
    },
    "cloudops": {
        "title": "CloudOps Operations View",
        "columns": ["Resource Type", "Account", "Status", "Last Event", "Alarms"],
        "keys": ["resource_type", "account_id", "status", "last_event", "alarm_count"],
    },
    "finops": {
        "title": "FinOps Optimization View",
        "columns": ["Resource Type", "Account", "Right-Size", "Savings Potential"],
        "keys": ["resource_type", "account_id", "right_size_rec", "savings_potential"],
    },
}

_MAX_DISPLAY_ROWS = 100


def render_persona_report(
    resources: list[dict[str, Any]],
    persona: str,
    console: Console | None = None,
) -> dict[str, Any]:
    """Render a persona-specific inventory report.

    Args:
        resources: List of resource dicts from inventory collectors.
        persona: One of "cto", "cfo", "cloudops", "finops".
        console: Rich Console instance. Creates a default one if None.

    Returns:
        Summary dict with persona, total_resources, total_accounts, total_types.

    Raises:
        ValueError: If persona is not in PERSONA_CONFIGS.
    """
    if console is None:
        console = Console()

    config = PERSONA_CONFIGS.get(persona)
    if not config:
        raise ValueError(f"Unknown persona: {persona}. Valid: {list(PERSONA_CONFIGS.keys())}")

    total = len(resources)
    accounts = len({r.get("account_id", "unknown") for r in resources})
    types = len({r.get("resource_type", "unknown") for r in resources})

    console.print(
        Panel(
            f"[bold]{config['title']}[/bold]\n{total} resources across {accounts} accounts ({types} resource types)",
            border_style="blue",
        )
    )

    table = Table(show_header=True, header_style="bold cyan")
    for col in config["columns"]:
        table.add_column(col)

    for resource in resources[:_MAX_DISPLAY_ROWS]:
        row = []
        for key in config["keys"]:
            val = resource.get(key, "\u2014")
            if isinstance(val, dict):
                val = str(val)[:50]
            row.append(str(val) if val is not None else "\u2014")
        table.add_row(*row)

    if total > _MAX_DISPLAY_ROWS:
        table.add_row(*["..." for _ in config["columns"]])

    console.print(table)

    return {
        "persona": persona,
        "total_resources": total,
        "total_accounts": accounts,
        "total_types": types,
    }


def render_all_personas(
    resources: list[dict[str, Any]],
    console: Console | None = None,
) -> list[dict[str, Any]]:
    """Render all 4 persona reports sequentially.

    Args:
        resources: List of resource dicts from inventory collectors.
        console: Shared Rich Console instance. Creates a default one if None.

    Returns:
        List of 4 summary dicts, one per persona.
    """
    if console is None:
        console = Console()
    return [render_persona_report(resources, persona, console) for persona in PERSONA_CONFIGS]
