"""
build_rules_book.py -- [2026-10-22] the user: a PDF we can add to later with all known situations, the avoid rules and
the do-not-trade list. The CONTENT lives in rules_book.json (edit it: add a row / change a status / add a changelog
line); this script only lays it out.
    python3 build_rules_book.py   -> rules_book.pdf (same folder)
"""
import json
from datetime import date
from pathlib import Path

from reportlab.lib import colors
from reportlab.lib.pagesizes import A4, landscape
from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet
from reportlab.lib.units import mm
from reportlab.platypus import PageBreak, Paragraph, SimpleDocTemplate, Spacer, Table, TableStyle

HERE = Path(__file__).resolve().parent
D = json.load(open(HERE / "rules_book.json"))
ss = getSampleStyleSheet()
H1 = ParagraphStyle("h1", parent=ss["Title"], fontSize=18, spaceAfter=4)
H2 = ParagraphStyle("h2", parent=ss["Heading2"], fontSize=13, spaceBefore=6, spaceAfter=4)
BODY = ParagraphStyle("b", parent=ss["BodyText"], fontSize=8.5, leading=11)
CELL = ParagraphStyle("c", parent=ss["BodyText"], fontSize=7.2, leading=8.8)
HEAD = ParagraphStyle("h", parent=CELL, fontName="Helvetica-Bold", textColor=colors.white)
STATUS = [("RECORD ONLY", "#1565c0"), ("V2", "#2e7d32"), ("AVOID", "#6a1b9a"), ("HAVE", "#2e7d32"), ("NONE", "#c62828"),
          ("PARTIAL", "#a15c00"), ("Star bot", "#1565c0"), ("blocked", "#a15c00"), ("recording", "#5b6675")]


def esc(t):
    return str(t).replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")


def status_cell(t):
    t = esc(t)
    for w, c in STATUS:
        if t.startswith(w):
            return Paragraph(f'<font color="{c}"><b>{w}</b></font>{t[len(w):]}', CELL)
    return Paragraph(t, CELL)


def table(header, rows, widths, status_col=None):
    data = [[Paragraph(esc(h), HEAD) for h in header]]
    for r in rows:
        data.append([status_cell(c) if i == status_col else Paragraph(esc(c), CELL) for i, c in enumerate(r)])
    t = Table(data, colWidths=[w * mm for w in widths], repeatRows=1)
    t.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#33475b")),
        ("GRID", (0, 0), (-1, -1), 0.4, colors.HexColor("#c5ccd6")),
        ("VALIGN", (0, 0), (-1, -1), "TOP"),
        ("ROWBACKGROUNDS", (0, 1), (-1, -1), [colors.white, colors.HexColor("#f4f6f9")]),
        ("LEFTPADDING", (0, 0), (-1, -1), 3), ("RIGHTPADDING", (0, 0), (-1, -1), 3),
        ("TOPPADDING", (0, 0), (-1, -1), 2), ("BOTTOMPADDING", (0, 0), (-1, -1), 2)]))
    return t


def footer(c, doc):
    c.saveState(); c.setFont("Helvetica", 7); c.setFillColor(colors.grey)
    c.drawString(12 * mm, 7 * mm, f"{D['title']} -- built {date.today().isoformat()} from rules_book.json")
    c.drawRightString(landscape(A4)[0] - 12 * mm, 7 * mm, f"page {doc.page}")
    c.restoreState()


def main():
    out = HERE / "rules_book.pdf"
    doc = SimpleDocTemplate(str(out), pagesize=landscape(A4), leftMargin=12 * mm, rightMargin=12 * mm,
                            topMargin=11 * mm, bottomMargin=12 * mm, title=D["title"])
    st = [Paragraph(esc(D["title"]), H1), Paragraph(esc(D["subtitle"]), BODY), Spacer(1, 4)]
    st += [Paragraph("&bull; " + esc(n), BODY) for n in D["notes"]]
    st += [Spacer(1, 6), Paragraph(f"1. Entry situations ({len(D['situations'])})", H2),
           table(["#", "Situation", "Example", "How it is recognized", "Rule now", "What we know (data)"], D["situations"],
                 [10, 38, 38, 52, 57, 78], status_col=4),
           PageBreak(), Paragraph(f"2. Avoid rules ({len(D['avoid_rules']) - 1} switches, avoid_rules.py)", H2),
           Paragraph("Each rule tested ALONE on the 2-year replay (base 2,012 buys -0.133%). Hits are logged on every BUY even when a rule is off.", BODY),
           Spacer(1, 3),
           table(["Rule", "Blocks a buy when", "Live", "2-year result with the rule ON", "Verdict"], D["avoid_rules"], [34, 72, 34, 92, 41]),
           Spacer(1, 8), Paragraph(f"3. Do NOT trade -- avoid list ({len(D['do_not_trade'])})", H2),
           table(["#", "Do not buy when...", "Evidence", "Strength"], D["do_not_trade"], [10, 85, 150, 28]),
           PageBreak(), Paragraph(f"4. Worked examples -- the last {len(D.get('worked_examples', [])) - 1} big losers vs the current rules", H2),
           Paragraph(esc(D.get("worked_examples_note", "")), BODY), Spacer(1, 3),
           table(["Day / stock", "The losing buy", "Day's best swing (low -> later high)", "TODAY (v2)", "+ situations", "+ situations + avoid", "Situations present"],
                 D.get("worked_examples", []), [28, 40, 46, 38, 38, 42, 41]),
           Spacer(1, 8), Paragraph("Changelog", H2),
           table(["Date", "Change"], D["changelog"], [22, 251])]
    doc.build(st, onFirstPage=footer, onLaterPages=footer)
    print(out)


if __name__ == "__main__":
    main()
