from pathlib import Path

import typer
from rich import print
from rich.table import Table

from aribaiq.datasets.loaders import load_table
from aribaiq.analytics.features import build_supplier_features
from aribaiq.analytics.scoring import score_suppliers
from aribaiq.analytics.suppliers import supplier_concentration
from aribaiq.governance.responsible_ai import (
    data_quality_report,
    representation_proxy_check,
)
from aribaiq.insights.cards import InsightCard, render_cards
from aribaiq.insights.prompts import build_genai_prompt

app = typer.Typer(help="aribaiq: AI-powered procurement analytics CLI")


@app.command()
def analyze(input_file: Path) -> None:
    """
    Analyze a supplier dataset and produce rankings, concentration signals,
    governance findings, and a GenAI-ready prompt.
    """
    df = load_table(input_file)

    features = build_supplier_features(df)
    ranked = score_suppliers(features)
    concentration = supplier_concentration(df)
    findings = data_quality_report(df) + representation_proxy_check(df)

    cards = [
        InsightCard(
            title="Supplier AIQ ranking",
            summary="Suppliers ranked using delivery, quality, ESG, and spend concentration signals.",
            data={"top_suppliers": ranked.head(5).to_dict(orient="records")},
        )
    ]

    if not concentration.empty:
        cards.append(
            InsightCard(
                title="Supplier concentration signals",
                summary="Category-level exposure and consolidation opportunities detected from spend distribution.",
                data={"top_categories": concentration.head(5).to_dict(orient="records")},
            )
        )

    if findings:
        cards.append(
            InsightCard(
                title="Responsible AI findings",
                summary="Lightweight governance checks detected data quality or representation issues.",
                data={"findings": [f.__dict__ for f in findings]},
            )
        )

    print("[bold green]Insight Summary[/bold green]")
    print(render_cards(cards))

    table = Table(title="Top Suppliers")
    columns = ["supplier_id", "aiq_score", "late_risk", "quality_risk", "esg_risk", "spend_share"]
    for col in columns:
        table.add_column(col)

    for _, row in ranked.head(10).iterrows():
        table.add_row(*[str(row[col]) for col in columns])

    print(table)

    if findings:
        print("\n[bold yellow]Governance Findings[/bold yellow]")
        for finding in findings:
            print(f"- [{finding.severity}] {finding.message}")

    payload = {
        "top_suppliers": ranked.head(5).to_dict(orient="records"),
        "concentration": concentration.head(5).to_dict(orient="records"),
        "findings": [f.__dict__ for f in findings],
    }

    print("\n[bold cyan]GenAI Prompt[/bold cyan]")
    print(build_genai_prompt(payload))


if __name__ == "__main__":
    app()
