# src/calibration/reports/strategies_report.py

from pathlib import Path
from typing import Any, Dict

from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, PageBreak
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib import colors


def _simple_kv_table(title: str, dct: Dict[str, Any]):
    rows = [["Key", "Value"]] + [[str(k), str(v)] for k, v in dct.items()]
    t = Table(rows, hAlign="LEFT")
    t.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, 0), colors.lightgrey),
        ("GRID", (0, 0), (-1, -1), 0.5, colors.grey),
        ("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
        ("VALIGN", (0, 0), (-1, -1), "TOP"),
    ]))
    return [Paragraph(title, getSampleStyleSheet()["Heading2"]), t, Spacer(1, 12)]


def generate_strategies_report_pdf(
    *,
    output_path: Path,
    context: Dict[str, Any],
    config: Dict[str, Any],
    results: Dict[str, Any],
):
    """Minimal v1 report. We'll enrich with charts/tables next iterations."""

    output_path.parent.mkdir(parents=True, exist_ok=True)

    styles = getSampleStyleSheet()
    doc = SimpleDocTemplate(str(output_path))

    story = []
    story.append(Paragraph("Calibration · Step 3 · Strategies", styles["Title"]))
    story.append(Spacer(1, 12))

    story.append(Paragraph(f"Status: {results.get('status')}", styles["Normal"]))
    story.append(Spacer(1, 12))

    for block in _simple_kv_table("Context", context):
        story.append(block)
    for block in _simple_kv_table("Configuration", config):
        story.append(block)

    story.append(Paragraph("Results (per strategy)", styles["Heading2"]))
    story.append(Spacer(1, 6))

    for r in results.get("results", []):
        story.append(Paragraph(
            f"<b>{r.get('strategy_id')}</b> — {r.get('status').upper()} — {r.get('message','')}",
            styles["Normal"],
        ))
        story.append(Spacer(1, 4))

        summary = {
            "n_windows": r.get("n_windows"),
            "oos_final_equity": r.get("oos_final_equity"),
            "oos_total_return_pct": r.get("oos_total_return_pct"),
            "oos_max_dd_worst_pct": r.get("oos_max_dd_worst_pct"),
        }
        for block in _simple_kv_table("Summary", summary):
            story.append(block)

        # Window table (first 20 to keep PDF light)
        windows = r.get("windows", [])
        if windows:
            rows = [["Window", "Test return %", "Sharpe", "Max DD %", "Trades", "Params"]]
            for w in windows[:20]:
                rows.append([
                    str(w.get("window")),
                    f"{float(w.get('return_pct',0.0)):.2f}",
                    f"{float(w.get('sharpe',0.0)):.2f}",
                    f"{float(w.get('max_dd_pct',0.0)):.2f}",
                    str(w.get("trades")),
                    str(w.get("params")),
                ])
            t = Table(rows, hAlign="LEFT", colWidths=[45, 75, 55, 65, 55, 240])
            t.setStyle(TableStyle([
                ("BACKGROUND", (0, 0), (-1, 0), colors.lightgrey),
                ("GRID", (0, 0), (-1, -1), 0.25, colors.grey),
                ("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
                ("VALIGN", (0, 0), (-1, -1), "TOP"),
            ]))
            story.append(Paragraph("Walk-Forward windows (first 20)", styles["Heading3"]))
            story.append(t)
            story.append(Spacer(1, 12))

        story.append(PageBreak())

    doc.build(story)
