"""
BizAnalyticsAI CLI — Command-line interface.

Usage:
    bizai profile data.csv
    bizai stats data.csv --col revenue
    bizai report data.csv --output report.html
    bizai montecarlo --revenue 50000 --growth 8 --fixed-costs 20000
"""

from __future__ import annotations

import json
import sys
from pathlib import Path

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

app     = Console()
cli     = typer.Typer(name="bizai", help="BizAnalyticsAI — Advanced Data Analysis CLI", rich_markup_mode="rich")
console = Console()


@cli.command("profile")
def profile_cmd(
    path:     str = typer.Argument(..., help="Path to CSV/Excel/Parquet file"),
    max_rows: int = typer.Option(0, "--max-rows", "-n", help="Limit rows (0 = all)"),
):
    """
    Profile a data file — show shape, dtypes, missing values, and insights.
    """
    import bizanalyticsai as bai

    console.print(f"[bold purple]Loading[/bold purple] {path} …")
    ext = Path(path).suffix.lower()

    if ext == ".csv":
        df = bai.read_csv(path)
    elif ext in (".xlsx", ".xls"):
        df = bai.read_excel(path)
    elif ext == ".parquet":
        df = bai.read_parquet(path)
    elif ext == ".json":
        df = bai.read_json(path)
    else:
        console.print(f"[red]Unsupported file type: {ext}[/red]")
        raise typer.Exit(1)

    if max_rows > 0:
        df = df.head(max_rows)

    desc = bai.describe(df)

    console.print(Panel(
        f"[bold]Rows:[/bold] {len(df):,}  |  [bold]Cols:[/bold] {len(df.columns)}\n"
        f"[bold]Numeric:[/bold] {len(desc.numeric_cols)}  |  [bold]Categorical:[/bold] {len(desc.cat_cols)}\n"
        f"[bold]Missing:[/bold] {int(df.isna().sum().sum()):,} values total",
        title="[bold purple]BizAnalyticsAI — Data Profile[/bold purple]",
        border_style="purple",
    ))

    tbl = Table(show_header=True, header_style="bold purple", border_style="dim")
    tbl.add_column("Column")
    tbl.add_column("Type")
    tbl.add_column("Null %")
    tbl.add_column("Unique")
    tbl.add_column("Flags")

    qual = bai.BizFrame(df).quality()
    for _, row in qual.iterrows():
        color = "green" if row["flags"] == "OK" else "red" if "HIGH_NULL" in str(row["flags"]) else "yellow"
        tbl.add_row(
            str(row["column"]),
            str(row["dtype"]),
            f"{row['null_pct']}%",
            str(row["unique"]),
            f"[{color}]{row['flags']}[/{color}]",
        )
    console.print(tbl)

    if desc.insights:
        console.print("\n[bold yellow]Insights:[/bold yellow]")
        for insight in desc.insights:
            console.print(f"  {insight}")


@cli.command("report")
def report_cmd(
    path:   str       = typer.Argument(..., help="Input CSV/Excel/Parquet"),
    output: str       = typer.Option("report.html", "--output", "-o", help="Output HTML file"),
    title:  str       = typer.Option("BizAnalyticsAI Report", "--title", help="Report title"),
):
    """Generate an HTML summary report from a data file."""
    import bizanalyticsai as bai

    ext = Path(path).suffix.lower()
    df  = bai.read_csv(path) if ext == ".csv" else bai.read_excel(path) if ext in (".xlsx",) else bai.read_parquet(path)
    bai.report.summary_report(df, title=title, output=output)
    console.print(f"[green]✓[/green] Report saved to [bold]{output}[/bold]")


@cli.command("montecarlo")
def montecarlo_cmd(
    revenue:     float = typer.Option(...,      "--revenue",     "-r", help="Initial monthly revenue"),
    growth:      float = typer.Option(...,      "--growth",      "-g", help="Monthly growth % (e.g. 8)"),
    fixed_costs: float = typer.Option(...,      "--fixed-costs", "-f", help="Fixed monthly costs"),
    var_costs:   float = typer.Option(20.0,     "--var-costs",         help="Variable costs % of revenue"),
    investment:  float = typer.Option(0.0,      "--investment",  "-i", help="Initial investment"),
    months:      int   = typer.Option(24,       "--months",      "-m", help="Simulation horizon (months)"),
    iterations:  int   = typer.Option(10_000,   "--iterations",        help="Number of iterations"),
    seed:        int   = typer.Option(None,     "--seed",              help="Random seed"),
):
    """Run a Monte Carlo financial simulation."""
    import bizanalyticsai as bai

    console.print("[bold purple]Running Monte Carlo simulation …[/bold purple]")
    result = bai.finance.montecarlo(
        initial_revenue=revenue,
        growth_pct=growth,
        fixed_costs=fixed_costs,
        variable_cost_pct=var_costs,
        initial_investment=investment,
        months=months,
        iterations=iterations,
        seed=seed,
    )

    console.print(Panel(
        f"[bold]P10 (pessimist):[/bold]  {result.p10:>15,.2f}\n"
        f"[bold]P50 (median):  [/bold]  {result.p50:>15,.2f}\n"
        f"[bold]P90 (optimist):[/bold]  {result.p90:>15,.2f}\n"
        f"[bold]Mean:          [/bold]  {result.mean:>15,.2f}\n"
        f"[bold]Positive prob: [/bold]  {result.positive_probability:.1f}%\n"
        f"[bold]Bankruptcy risk:[/bold] {result.bankruptcy_probability:.1f}%",
        title=f"[bold purple]Monte Carlo — {months}mo / {iterations:,} iterations[/bold purple]",
        border_style="purple",
    ))


@cli.command("version")
def version_cmd():
    """Show BizAnalyticsAI version."""
    import bizanalyticsai
    console.print(f"BizAnalyticsAI [bold purple]{bizanalyticsai.__version__}[/bold purple]")


def main():
    cli()


if __name__ == "__main__":
    main()
