from __future__ import annotations

import json
import typer
from rich import print
from pathlib import Path

from .p2p.events import P2PEvent
from .process_mining.mining import variants, lead_time, bottlenecks
from .genai.insights import build_procurement_insights, render_insights_text

app = typer.Typer(help="aribapulse - P2P analytics + process mining + GenAI insights + ESG hooks")


@app.command()
def analyze_events(events_json: Path):
    """
    Analyze a JSON list of P2P events.
    JSON format: [{case_id, event_type, ts, supplier_id?, amount?, currency?, metadata?}, ...]
    """
    raw = json.loads(events_json.read_text())
    events = [P2PEvent.model_validate(x) for x in raw]

    top_vars = variants(events, max_variants=10)
    lt = lead_time(events, start="PO_CREATED", end="PAYMENT_SENT")
    slow = bottlenecks(lt, top_n=10)

    # ESG flags are optional; for demo we emit none.
    insights = build_procurement_insights(top_vars, slow, esg_flags=[])

    print("[bold]Insights[/bold]")
    print(render_insights_text(insights))

    print("\n[bold]Top Variants[/bold]")
    for v in top_vars:
        print(f"- {v.count}x :: {' -> '.join(v.variant)}")


if __name__ == "__main__":
    app()

