from __future__ import annotations

import sys
import json
from datetime import datetime

import click

from .._client import get_client, handle_errors
from .._formatter import to_dict


@click.group()
def ci() -> None:
    """CI/CD pipeline helpers.

    \b
    Examples:
      stratix ci report
      stratix ci report --format json
      stratix ci report --output summary.md
    """


@ci.command("report")
@click.option(
    "--output",
    "-o",
    "output_file",
    default=None,
    type=click.Path(),
    help="Output file path.",
)
@click.option("--limit", default=10, type=int, help="Number of recent evaluations to include.")
@click.option("--dry-run", is_flag=True, default=False, help="Preview without fetching data.")
@click.pass_context
@handle_errors
def ci_report(ctx: click.Context, output_file: str | None, limit: int, dry_run: bool) -> None:
    """Generate a CI summary report.

    Outputs a markdown report suitable for GitHub Actions job summaries.

    \b
    Examples:
      stratix ci report
      stratix ci report --output summary.md
      stratix ci report --limit 20 --format json
      stratix ci report >> $GITHUB_STEP_SUMMARY
    """
    if dry_run:
        click.echo("[dry-run] Would generate CI report")
        return

    client = get_client(ctx)

    evals_resp = client.evaluations.get_many(page_size=limit, sort_by="submitted_at", order="desc")
    if evals_resp is None or not evals_resp.evaluations:
        click.echo("No evaluations found for report.", err=True)
        sys.exit(1)

    evaluations = evals_resp.evaluations

    if ctx.obj["output_format"] == "json":
        report = {
            "generated_at": datetime.utcnow().isoformat(),
            "total_evaluations": len(evaluations),
            "evaluations": [to_dict(e) for e in evaluations],
            "summary": {
                "passed": sum(1 for e in evaluations if e.status == "success"),
                "failed": sum(1 for e in evaluations if e.status == "failure"),
                "pending": sum(1 for e in evaluations if e.status in ("pending", "in-progress")),
            },
        }
        content = json.dumps(report, indent=2, default=str)
    else:
        content = _build_markdown_report(evaluations)

    if output_file:
        with open(output_file, "w") as f:
            f.write(content)
        click.echo(f"Report written to {output_file}")
    else:
        click.echo(content)


def _build_markdown_report(evaluations: list) -> str:
    lines = []
    lines.append("# Stratix Evaluation Report")
    lines.append("")
    lines.append(f"Generated: {datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S UTC')}")
    lines.append("")

    passed = sum(1 for e in evaluations if e.status == "success")
    failed = sum(1 for e in evaluations if e.status == "failure")
    pending = sum(1 for e in evaluations if e.status in ("pending", "in-progress"))

    lines.append("## Summary")
    lines.append("")
    lines.append(f"| Metric | Count |")
    lines.append(f"|--------|-------|")
    lines.append(f"| Total | {len(evaluations)} |")
    lines.append(f"| Passed | {passed} |")
    lines.append(f"| Failed | {failed} |")
    lines.append(f"| Pending | {pending} |")
    lines.append("")

    lines.append("## Evaluations")
    lines.append("")
    lines.append("| ID | Model | Benchmark | Status | Accuracy |")
    lines.append("|-----|-------|-----------|--------|----------|")

    for e in evaluations:
        eid = getattr(e, "id", "-")[:12]
        model = getattr(e, "model_name", "-") or "-"
        benchmark = getattr(e, "benchmark_name", "-") or "-"
        status = getattr(e, "status", "-") or "-"
        accuracy = getattr(e, "accuracy", None)
        acc_str = f"{accuracy:.2%}" if accuracy is not None else "-"
        emoji = "+" if status == "success" else ("-" if status == "failure" else " ")
        lines.append(f"| `{eid}` | {model} | {benchmark} | {emoji} {status} | {acc_str} |")

    lines.append("")
    lines.append("---")
    lines.append("*Generated by `stratix ci report`*")

    return "\n".join(lines)
