"""The real AGA proposal rebuilt as a scene: same sheets and logic as the CKEditor template + mapping.py.

Sizes come from the customer's current PDF (CSS px * 0.75 = pt), A4 landscape 841.89 x 595.28 pt.
Asset references are ``aga:<file name>``; the seed replaces them with uploaded asset ids.
"""

from __future__ import annotations

import json
from pathlib import Path
from typing import Any

W, H = 841.89, 595.28
INTER_ASC, INTER_DESC = 1984 / 2048, 494 / 2048

PALETTE = ["#0D2B5E", "#C9922A", "#1A7A6E", "#7D0302"]
NAVY = "#1B2A4A"
TEAL = "#005670"
GOLD = "#E0A63A"
GREY_TEXT = "#6B7280"
LOOP_COLOR = f"Palette[loop.index0 % {len(PALETTE)}]"

LOGO = "aga:14dae7347eb54f6e9282b24052a87719.webp"
MOSAIC_LIGHT = "aga:e64abee5f3894af39556a7b7fd486d97.webp"
MOSAIC_DARK = "aga:bdfc6f81e0a845278f63f9825ba6aca4.webp"
COVER_ART = "aga:1525c811c35049cea5bda1c9931b9177.webp"
STRIP = "aga:1ba33be97eb74d3c8b6223fda9124660.webp"
HEADER_TEAL = "aga:c4a76f4eaef345e19b3cc60c82161cb5.webp"
HEADER_ORANGE = "aga:68aa7049c7a7416cb783e833f0fdb1f0.webp"

PROFILE_PAGES = [
    ("100% Equity Target", "aga:06f727afbd5a4476aae96f4a5be3d3e9.webp"),
    ("80% Equity Target", "aga:747d7c8e3d5242d6b1b832bc0f69a05f.webp"),
    ("70% Equity Target", "aga:42e767b7108145ebaf5d64f9762e94e1.webp"),
    ("50% Equity Target", "aga:58bd982d15e141e69fa74e163618d311.webp"),
    ("30% Equity Target", "aga:bdedf018ca4e4df48387d1bfee08f67d.webp"),
    ("100% Fixed Income", "aga:9da40cb7f204450cb3ab8c56996fc514.webp"),
]

_seq = 0


def _id(prefix: str) -> str:
    global _seq
    _seq += 1
    return f"{prefix}-{_seq}"


def solid(color: str) -> list[dict[str, Any]]:
    return [{"type": "solid", "color": color}]


def run(text: str, size: float, color: str, weight: int = 400, spacing: float = 0, lh: float = 1.2) -> dict[str, Any]:
    return {
        "text": text,
        "style": {"fontSize": size, "color": color, "fontWeight": weight, "letterSpacing": spacing, "lineHeight": lh},
    }


def top_for_baseline(baseline: float, size: float, lh: float) -> float:
    """Box top so that the first line sits on ``baseline`` (half-leading, as in spec/text-layout.md)."""
    return baseline - ((lh - INTER_ASC - INTER_DESC) / 2 + INTER_ASC) * size


def text(
    txt: str,
    x: float,
    baseline: float,
    size: float,
    color: str,
    *,
    w: float = 400,
    weight: int = 400,
    spacing: float = 0,
    lh: float = 1.2,
    align: str = "left",
    **extra: Any,
) -> dict[str, Any]:
    lines = txt if isinstance(txt, list) else [txt]
    return {
        "id": _id("t"),
        "type": "text",
        "x": x,
        "y": top_for_baseline(baseline, size, lh),
        "w": w,
        "h": size * lh * len(lines),
        "autoSize": "height",
        "content": [{"align": align, "runs": [run(ln, size, color, weight, spacing, lh)]} for ln in lines],
        **extra,
    }


def centered(
    txt: str, cx: float, baseline: float, size: float, color: str, w: float = 760, **kw: Any
) -> dict[str, Any]:
    return text(txt, cx - w / 2, baseline, size, color, w=w, align="center", **kw)


def image(
    asset: str, x: float, y: float, w: float, h: float, fit: str = "cover", focal: str = "center"
) -> dict[str, Any]:
    return {
        "id": _id("img"),
        "type": "image",
        "x": x,
        "y": y,
        "w": w,
        "h": h,
        "assetId": asset,
        "fit": fit,
        "focal": focal,
    }


def rect(x: float, y: float, w: float, h: float, color: str | None = None, **extra: Any) -> dict[str, Any]:
    node = {"id": _id("r"), "type": "rect", "x": x, "y": y, "w": w, "h": h, **extra}
    if color:
        node["fills"] = solid(color)
    return node


def sheet(sid: str, name: str, children: list[dict[str, Any]], bg: str = "#FFFFFF", **extra: Any) -> dict[str, Any]:
    return {
        "id": sid,
        "name": name,
        "format": "A4",
        "orientation": "landscape",
        "size": {"w": W, "h": H},
        "background": {"type": "solid", "color": bg},
        "pageNumbering": {"skip": True},
        "children": children,
        **extra,
    }


def image_page(sid: str, name: str, asset: str, **extra: Any) -> dict[str, Any]:
    return sheet(sid, name, [image(asset, 0, 0, W, H)], **extra)


def header_small(label: str, title: str) -> list[dict[str, Any]]:
    return [
        rect(0, 0, W, 48.2, NAVY),
        image(STRIP, 0, 0, W, 48.2),
        text(label, W - 430, 28, 11.25, "#FFFFFF", w=400, weight=700, spacing=0.375, align="right", name="Section"),
        rect(0, 48.2, W, 56.7, TEAL),
        centered(title, W / 2, 83, 19.5, "#FFFFFF", weight=700, spacing=0.75, name="Title"),
    ]


def footer() -> list[dict[str, Any]]:
    return [
        rect(0, 521.6, W, 36.8, "#58585A"),
        text("accuvest.com", 30, 543, 9.75, "#FFFFFF", w=300, name="Site"),
        text("Tel 925-930-2882", W - 330, 543, 9.75, "#FFFFFF", w=300, align="right", name="Phone"),
    ]


def divider(sid: str, name: str, title: str, bg: str, header: str, mosaic_y: float = 528) -> dict[str, Any]:
    return sheet(
        sid,
        name,
        [
            image(header, 0, 0, W, 107),
            image(LOGO, 24, 7, 210, 94, fit="contain"),
            centered(title, W / 2, 369, 25.5, GOLD, weight=600, spacing=1.125),
            image(MOSAIC_DARK, 677, mosaic_y, 135, 36, fit="contain"),
        ],
        bg=bg,
    )


def spacer(h: float) -> dict[str, Any]:
    return {"id": _id("sp"), "type": "rect", "w": 10, "h": h}


def flow_text(
    txt: str, w: float, size: float, color: str, weight: int = 400, lh: float = 1.2, **extra: Any
) -> dict[str, Any]:
    lines = txt if isinstance(txt, list) else [txt]
    return {
        "id": _id("t"),
        "type": "text",
        "w": w,
        "h": size * lh,
        "autoSize": "height",
        "sizing": {"h": "hug"},
        "content": [{"runs": [run(ln, size, color, weight, 0, lh)]} for ln in lines],
        **extra,
    }


def cover() -> dict[str, Any]:
    w = 460
    body = "#3D4A55"
    flow = {
        "id": "cover-copy",
        "type": "frame",
        "name": "Copy (flows with the data)",
        "x": 346,
        "y": 257,
        "w": w,
        "h": 200,
        "sizing": {"h": "hug"},
        "layout": {"mode": "vertical", "gap": 0, "align": "start"},
        "children": [
            flow_text("{{client_full_name}}", w, 31.5, "#17466B", 800, 1.15, name="Client name"),
            spacer(4.5),
            flow_text("We have identified you as a…", w, 11.25, body, lh=1.5),
            spacer(7.5),
            flow_text("{{recommended_strategy}}", w, 22.5, "#D4622C", 700, 1.2, name="Investment profile"),
            spacer(3),
            flow_text(
                [
                    "and have crafted a personalized investment plan built to align",
                    "with your financial goals and long-term vision.",
                ],
                w,
                11.25,
                body,
                lh=1.5,
            ),
            spacer(16.5),
            flow_text(
                "You seek {{suitability_profile.description}}",
                w,
                11.25,
                body,
                lh=1.5,
                visibleIf="suitability_profile.description",
                name="Profile description",
            ),
        ],
    }
    return sheet(
        "cover",
        "Cover",
        [
            image(COVER_ART, 0, 0, 286, 113, focal="left top"),
            rect(0, 113, W, 74, "#0D5B72"),
            image(COVER_ART, 0, 187, 286, H - 187, focal="left bottom"),
            image(LOGO, 24, 114, 165, 73, fit="contain"),
            text("YOUR FUTURE  AWAITS", 370, 159, 24, GOLD, w=480, weight=600, spacing=0.75, name="Tagline"),
            flow,
            image(MOSAIC_LIGHT, 671, 504, 135, 36, fit="contain"),
        ],
    )


def badge(cx: float, y: float, txt: str) -> dict[str, Any]:
    return {
        "id": _id("badge-col"),
        "type": "frame",
        "x": cx - 72.7,
        "y": y,
        "w": 145.4,
        "h": 14.1,
        "layout": {"mode": "horizontal", "justify": "center", "align": "start"},
        "children": [
            {
                "id": _id("badge"),
                "type": "frame",
                "w": 40,
                "h": 14.1,
                "sizing": {"w": "hug", "h": "hug"},
                "fills": solid(NAVY),
                "cornerRadius": 3.75,
                "layout": {"mode": "horizontal", "padding": {"top": 2.5, "right": 7.5, "bottom": 2.5, "left": 7.5}},
                "children": [
                    {
                        "id": _id("t"),
                        "type": "text",
                        "w": 40,
                        "h": 10,
                        "autoSize": "width",
                        "sizing": {"w": "hug", "h": "hug"},
                        "content": [{"runs": [run(txt, 8.25, "#FFFFFF", 700, 0, 1.1)]}],
                    }
                ],
            }
        ],
    }


def allocation_page() -> dict[str, Any]:
    tx = 374.1
    col2, col3 = 592.3, 737.7
    rows = [
        ("Fixed Income", "{{fixed_income_pct_view}}", "{{fixed_income_pct}}%", 273.5, 304.6, 292),
        ("Alternatives", "{{alternatives_pct_view}}", "{{alternatives_pct}}%", 304.6, 335.6, 323),
        ("Cash", "{{cash_pct_view}}", "{{cash_pct}}%", 335.6, 366.7, 354),
    ]
    line = {"color": "#E5E7EB", "width": 0.75}
    kids: list[dict[str, Any]] = [
        *header_small("YOUR PROPOSED PORTFOLIO", "YOUR {{risk_profile|upper}} PORTFOLIO ALLOCATION"),
        centered(
            "A diversified mix of asset classes designed to balance growth opportunities with risk management. "
            "Your portfolio will be actively managed to help you stay on track toward your goals while adapting "
            "to changing market conditions.",
            W / 2,
            134,
            9,
            GREY_TEXT,
            w=450,
            lh=1.6,
        ),
        centered("CURRENT ALLOCATION", 187.1, 194, 7.5, NAVY, w=240, weight=800, spacing=1.5),
        {
            "id": "allocation-pie",
            "type": "chart",
            "name": "AllocationPie",
            "chartType": "donut",
            "x": 187.1 - 125,
            "y": 316.6 - 125,
            "w": 250,
            "h": 250,
            "outerRadius": 90,
            "innerRadius": 52.5,
            "palette": PALETTE,
            "remainderColor": "#B0BEC5",
            "segments": [
                {"value": "equity_pct", "label": "Equity"},
                {"value": "fixed_income_pct", "label": "Fixed Income"},
                {"value": "alternatives_pct", "label": "Alternatives"},
                {"value": "cash_pct", "label": "Cash"},
            ],
            "center": {"line1": "TOTAL PORTFOLIO", "line2": "VALUE", "value": "{{TotalCurrency}}"},
        },
    ]
    for label, x, color in (
        ("Equity", 59.4, "#002C61"),
        ("Fixed Income", 114.7, "#FFBB00"),
        ("Alternatives", 198.3, "#6BA460"),
        ("Cash", 277.2, "#00878E"),
    ):
        kids.append({"id": _id("dot"), "type": "ellipse", "x": x, "y": 443.4, "w": 12, "h": 12, "fills": solid(color)})
        kids.append(text(label, x + 17.5, 454, 8.25, "#374151", w=80, weight=500))
    kids += [
        centered("ALLOCATION DETAILS", col2, 194, 7.5, NAVY, w=300, weight=800, spacing=1.5),
        rect(tx, 207.1, 436.3, 23.1, NAVY),
        text("Asset Class", 383, 221, 8.25, "#FFFFFF", w=130, weight=700),
        centered("Market Value", col2, 221, 8.25, "#FFFFFF", w=140, weight=700),
        centered("% Assets", col3, 221, 8.25, "#FFFFFF", w=140, weight=700),
        rect(tx, 230.2, 436.3, 43.3, strokes=[line], strokeSides=["bottom"], name="Row equity"),
        text("Equity", 383, 246, 9, NAVY, w=130, weight=700),
        {
            "id": "equity-note",
            "type": "text",
            "x": 383,
            "y": top_for_baseline(255, 7.5, 1.2),
            "w": 128,
            "h": 18,
            "autoSize": "height",
            "content": [
                {
                    "runs": [
                        run("★", 7.5, "#C8A84E"),
                        run(" {{equity_pct_view}} allocated to equity assets", 7.5, "#9CA3AF"),
                    ]
                }
            ],
        },
        centered("{{equity_pct_view}}", col2, 255, 9, "#000000", w=140, weight=600),
        badge(col3, 245.2, "{{equity_pct}}%"),
    ]
    for name, value, pct, y0, y1, base in rows:
        kids += [
            rect(tx, y0, 436.3, y1 - y0, strokes=[line], strokeSides=["bottom"], name=f"Row {name}"),
            text(name, 383, base, 9, NAVY, w=130, weight=700),
            centered(value, col2, base, 9, "#000000", w=140, weight=600),
            badge(col3, base - 9.4, pct),
        ]
    kids += [
        rect(tx, 366.7, 436.3, 30.7, "#F0F2F5"),
        text("Total", 383, 386, 8.25, NAVY, w=130, weight=700),
        centered("{{TotalCurrency}}", col2, 386, 12, NAVY, w=140, weight=700),
        badge(col3, 375.8, "100%"),
        *footer(),
    ]
    return sheet("allocation", "Your Proposed Portfolio", kids)


def bullet_row(field: str, w: float, size: str, gap: str, dot: str) -> dict[str, Any]:
    """A bullet row; an empty bullet takes no space (``if not bullet: continue`` in mapping.py)."""
    return {
        "id": _id("bullet"),
        "type": "frame",
        "w": w,
        "h": 10,
        "sizing": {"h": "hug"},
        "visibleIf": field,
        "layout": {"mode": "horizontal", "gap": 6, "align": "start"},
        "children": [
            {
                "id": _id("dot-holder"),
                "type": "frame",
                "w": 6,
                "h": 8,
                "sizing": {"h": "hug"},
                "layout": {"mode": "vertical", "padding": {"top": 2.5}},
                "children": [
                    {
                        "id": _id("dot"),
                        "type": "ellipse",
                        "w": 6,
                        "h": 6,
                        "bind": {"color": LOOP_COLOR, "w": dot, "h": dot},
                        "fills": solid(PALETTE[0]),
                    }
                ],
            },
            {
                "id": _id("t"),
                "type": "text",
                "w": w - 12,
                "h": 10,
                "autoSize": "height",
                "sizing": {"h": "hug"},
                "bind": {"fontSize": size},
                "content": [{"runs": [run("{{" + field + "}}", 7.5, GREY_TEXT, 400, 0, 1.4)]}],
            },
        ],
    }


def cards(source: str, name_f: str, pct_tpl: str, bullets: list[str], *, compact: str, fi: bool) -> dict[str, Any]:
    """_equity_custom_box / _fixed_income_custom_box: one card per item, compact from 4 items."""
    x, w = 361.0, 451.0
    inner = w - 3 - 24
    gap = "7.5" if fi else "6"
    pad_v = "7.5" if fi else "6"
    top = "4.5" if fi else "3"
    line = "3" if fi else "2.25"
    bullet_font = "7.5" if fi else "6.75"
    bullet_size = "9" if fi else "7.5"
    card = {
        "id": _id("card"),
        "type": "frame",
        "name": "Card",
        "w": w,
        "h": 40,
        "sizing": {"w": "fixed", "h": "hug"},
        "cornerRadius": 9,
        "strokes": [{"color": "#E5E7EB", "width": 0.75}],
        "layout": {"mode": "horizontal", "align": "stretch"},
        "children": [
            {
                "id": _id("accent"),
                "type": "rect",
                "name": "Accent",
                "w": 3,
                "h": 10,
                "sizing": {"h": "fill"},
                "cornerRadius": [9, 0, 0, 9],
                "fills": solid(PALETTE[0]),
                "bind": {"color": LOOP_COLOR},
            },
            {
                "id": _id("body"),
                "type": "frame",
                "w": w - 3,
                "h": 10,
                "sizing": {"w": "fill", "h": "hug"},
                "layout": {"mode": "vertical", "padding": {"top": 10.5, "right": 12, "bottom": 10.5, "left": 12}},
                "bind": {
                    "padding.top": f"{compact} ? {pad_v} : 10.5",
                    "padding.bottom": f"{compact} ? {pad_v} : 10.5",
                    "gap": f"{compact} ? {top} : 7.5",
                },
                "children": [
                    {
                        "id": _id("head"),
                        "type": "frame",
                        "w": inner,
                        "h": 16,
                        "sizing": {"h": "hug"},
                        "layout": {"mode": "horizontal", "align": "start"},
                        "children": [
                            {
                                "id": _id("name"),
                                "type": "text",
                                "w": inner * 0.75,
                                "h": 14,
                                "autoSize": "height",
                                "sizing": {"h": "hug"},
                                "bind": {"fontSize": f"{compact} ? 10.5 : 11.25"},
                                "content": [{"runs": [run("{{c." + name_f + "}}", 11.25, NAVY, 800)]}],
                            },
                            {
                                "id": _id("pct"),
                                "type": "text",
                                "w": inner * 0.25,
                                "h": 14,
                                "autoSize": "height",
                                "sizing": {"h": "hug"},
                                "bind": {"fontSize": f"{compact} ? 12.75 : 14.25", "color": LOOP_COLOR},
                                "content": [{"align": "right", "runs": [run(pct_tpl, 14.25, PALETTE[0], 800)]}],
                            },
                        ],
                    },
                    {
                        "id": _id("bullets"),
                        "type": "frame",
                        "w": inner,
                        "h": 10,
                        "sizing": {"h": "hug"},
                        "layout": {"mode": "vertical"},
                        "bind": {"gap": f"{compact} ? {line} : 4.5"},
                        "children": [
                            bullet_row(
                                f"c.{b}",
                                inner,
                                f"{compact} ? {bullet_font} : {bullet_size}",
                                line,
                                f"{compact} ? 5 : 6",
                            )
                            for b in bullets
                        ],
                    },
                ],
            },
        ],
    }
    return {
        "id": _id("cards"),
        "type": "repeater",
        "name": "Cards",
        "x": x,
        "y": 160,
        "w": w,
        "h": 355,
        "source": source,
        "as": "c",
        "direction": "vertical",
        "gap": 12,
        "bind": {"gap": f"{compact} ? {gap} : 12"},
        "overflow": "clip",
        "item": {"h": 40, "sizing": {"h": "hug"}, "children": [card]},
    }


def legend(source: str, name_f: str, size: float) -> dict[str, Any]:
    return {
        "id": _id("legend"),
        "type": "repeater",
        "name": "Legend",
        "x": 116,
        "y": 412,
        "w": 180,
        "h": 100,
        "source": source,
        "as": "c",
        "direction": "vertical",
        "gap": 4.5,
        "overflow": "clip",
        "item": {
            "h": 12,
            "children": [
                {
                    "id": _id("legend-dot"),
                    "type": "ellipse",
                    "x": 0,
                    "y": 2,
                    "w": 8,
                    "h": 8,
                    "fills": solid(PALETTE[0]),
                    "bind": {"color": LOOP_COLOR},
                },
                {
                    "id": _id("legend-name"),
                    "type": "text",
                    "x": 14,
                    "y": 0,
                    "w": 166,
                    "h": 12,
                    "verticalAlign": "middle",
                    "overflowMode": "ellipsis",
                    "maxLines": 1,
                    "content": [{"runs": [run("{{c." + name_f + "}}", size, "#4B5563", 400, 0, 1.3)]}],
                },
            ],
        },
    }


def custom_page(
    sid: str, title: str, subtitle: str, caption: str, chart: dict[str, Any], rest: list[dict[str, Any]]
) -> dict[str, Any]:
    return sheet(
        sid,
        title.title(),
        [
            *header_small("YOUR PROPOSED PORTFOLIO", title),
            centered(subtitle, W / 2, 132, 9, GREY_TEXT, lh=1.6),
            centered(caption, 186, 165, 7.5, GREY_TEXT, w=300, weight=700, spacing=1.125),
            {
                "id": _id("pie"),
                "type": "chart",
                "chartType": "donut",
                "x": 186 - 120,
                "y": 172,
                "w": 240,
                "h": 240,
                "outerRadius": 90,
                "innerRadius": 52.5,
                "palette": PALETTE,
                "remainderColor": "#B0BEC5",
                **chart,
            },
            *rest,
            *footer(),
        ],
        visibleIf="not use_default_model",
    )


def macro_page() -> dict[str, Any]:
    bar_x, bar_w = 179.3, 186.5
    pct = "(m.bar_pct > 100 ? 100 : (m.bar_pct > 0 ? m.bar_pct : 0))"
    return sheet(
        "macro",
        "Macro Market Outlook",
        [
            *header_small("MARKET OVERVIEW", '{{now|date:"LLLL"|upper}} MACRO MARKET OUTLOOK'),
            centered(
                "Comprehensive overview of the important factors driving risk taking decisions.",
                W / 2,
                132,
                9,
                GREY_TEXT,
            ),
            {
                "id": "macro-rows",
                "type": "repeater",
                "name": "MacroOutlookBlock",
                "x": 187,
                "y": 153,
                "w": 460,
                "h": 360,
                "source": "macro_outlook",
                "as": "m",
                "direction": "vertical",
                "gap": 0,
                "overflow": "clip",
                "item": {
                    "h": 33,
                    "children": [
                        {
                            "id": "m-icon",
                            "type": "image",
                            "x": 0,
                            "y": 1,
                            "w": 22.5,
                            "h": 22.5,
                            "src": "m.icon",
                            "fit": "contain",
                            "visibleIf": "m.icon",
                        },
                        {
                            "id": "m-title",
                            "type": "text",
                            "x": 30,
                            "y": 0,
                            "w": 142,
                            "h": 23,
                            "verticalAlign": "middle",
                            "overflowMode": "ellipsis",
                            "maxLines": 2,
                            "content": [{"runs": [run("{{m.title}}", 11.25, NAVY, 700, 0, 1.2)]}],
                        },
                        rect(bar_x, 5.9, bar_w, 12, "#ECEFF1", name="Track"),
                        {
                            "id": "m-bar",
                            "type": "rect",
                            "x": bar_x,
                            "y": 5.9,
                            "w": bar_w,
                            "h": 12,
                            "fills": solid("#000000"),
                            "bind": {"w": f"{pct} / 100 * {bar_w}", "color": 'm.color|default:"#000000"'},
                        },
                        {
                            "id": "m-status",
                            "type": "text",
                            "x": 384,
                            "y": 0,
                            "w": 76,
                            "h": 23,
                            "verticalAlign": "middle",
                            "content": [
                                {"runs": [run("{{m.status_label|default:m.status}}", 11.25, NAVY, 400, 0, 1.2)]}
                            ],
                        },
                    ],
                },
            },
            *footer(),
        ],
    )


def disclosures_page() -> dict[str, Any]:
    paragraphs = (Path(__file__).parent / "aga_disclosures.txt").read_text(encoding="utf-8").strip().split("\n")
    return sheet(
        "disclosures",
        "Disclosures",
        [
            image(HEADER_TEAL, 0, 0, W, 107),
            image(LOGO, 24, 7, 210, 94, fit="contain"),
            text("DISCLOSURES", 36, 172, 21, GOLD, w=500, weight=600, spacing=0.75),
            {
                "id": "disclosures-text",
                "type": "text",
                "x": 36,
                "y": top_for_baseline(203, 9, 1.6),
                "w": 770,
                "h": 300,
                "autoSize": "height",
                "paragraphSpacing": 10.5,
                "content": [{"runs": [run(p, 9, "#FFFFFF", 400, 0, 1.6)]} for p in paragraphs],
            },
            image(MOSAIC_DARK, 671, 517, 135, 36, fit="contain"),
        ],
        bg=TEAL,
    )


def build_scene() -> dict[str, Any]:
    global _seq
    _seq = 0
    equity_compact = "SleevesSorted|count >= 4"
    fi_compact = "FixedIncomeHoldings|count >= 4"
    sheets = [
        cover(),
        image_page("what-we-do", "What we do", "aga:8f99e903a7f3483b8e22e3ea1f2d3641.webp"),
        image_page("team", "Investment team", "aga:9ff05b1d3e0648568b5650ef6d042661.webp"),
        divider("proposal-divider", "Your Portfolio Proposal", "YOUR PORTFOLIO PROPOSAL", TEAL, HEADER_TEAL),
        image_page("construct", "How we construct portfolios", "aga:e61f10c4dbf441c3bcad37e15bc9cec5.webp"),
        image_page("diversification", "Diversification", "aga:3c5edb837a544d1e891f039c8ff29837.webp"),
        allocation_page(),
        custom_page(
            "custom-equity",
            "YOUR EQUITY PORTFOLIO ALLOCATION",
            "How your equity allocation is distributed across your active equity models.",
            "EQUITY MODEL ALLOCATION",
            {"source": "SleevesSorted", "valueField": "allocation_pct", "labelField": "model_name"},
            [
                legend("SleevesSorted", "model_name", 7.5),
                cards(
                    "SleevesSorted",
                    "model_name",
                    "{{c.allocation_pct}}%",
                    ["model_bullet1", "model_bullet2", "model_bullet3"],
                    compact=equity_compact,
                    fi=False,
                ),
            ],
        ),
        custom_page(
            "custom-fixed-income",
            "FIXED INCOME & ALTERNATIVES ALLOCATION",
            "How the non-equity sleeves are structured within your Growth & Income portfolio.",
            "TOTAL PORTFOLIO ALLOCATION",
            {"source": "FixedIncomeHoldings", "valueField": "pct_i", "labelField": "name"},
            [
                legend("FixedIncomeHoldings", "name", 8.25),
                cards(
                    "FixedIncomeHoldings",
                    "name",
                    "{{c.pct_n}}",
                    ["bullet1", "bullet2", "bullet3"],
                    compact=fi_compact,
                    fi=True,
                ),
            ],
        ),
    ]
    for label, asset in PROFILE_PAGES:
        slug = label.lower().replace("% ", "-").replace(" ", "-")
        sheets.append(
            image_page(
                f"profile-{slug}",
                f"Profile: {label}",
                asset,
                visibleIf=f'use_default_model and suitability_profile.label == "{label}"',
            )
        )
    sheets += [
        image_page("support", "How we support you", "aga:c0cc9477da9b41f88067357c035bcf61.webp"),
        divider("market-divider", "Market Overview", "MARKET OVERVIEW", "#58585A", HEADER_ORANGE),
        macro_page(),
        image_page("earnings", "Earnings + profits", "aga:1e344e74067543ceabdc1e4dc732c895.webp"),
        image_page("declines", "Short-term declines", "aga:3ba188931c4a48a183547d4e5b81339e.webp"),
        image_page("allocations", "Stock allocations", "aga:ed0e61849dfc45a499a8d3997708f7ff.webp"),
        image_page("strategies", "Investment strategies", "aga:f930d7584cf54db2b07446c7f4526b04.webp"),
        disclosures_page(),
    ]
    return {
        "formatVersion": 1,
        "meta": {"title": "Portfolio proposal for {{client_full_name}}", "author": "Accuvest Global Advisors"},
        "defaults": {"fontFamily": "Inter", "fontSize": 9, "color": "#3D4A55", "lineHeight": 1.2, "locale": "en"},
        "sheets": sheets,
    }


def _s(key: str, **kw: Any) -> dict[str, Any]:
    return {"key": key, "type": "string", "nullable": True, **kw}


def _n(key: str, **kw: Any) -> dict[str, Any]:
    return {"key": key, "type": "number", "nullable": True, **kw}


def _b(key: str, **kw: Any) -> dict[str, Any]:
    return {"key": key, "type": "bool", "nullable": True, **kw}


def _objects(key: str, fields: list[dict[str, Any]]) -> dict[str, Any]:
    return {"key": key, "type": "array", "nullable": True, "items": {"type": "object", "fields": fields}}


def build_variables() -> list[dict[str, Any]]:
    """The keys of the AGA proposal JSON; derived variables replace the Python in mapping.py."""
    sleeve = [
        _s("equity_profiles_id"),
        _n("allocation_pct"),
        _s("model_name"),
        _s("model_type"),
        _s("model_description"),
        _s("model_bullet1"),
        _s("model_bullet2"),
        _s("model_bullet3"),
        _n("min_investment"),
    ]
    holding = [
        _s("id"),
        _s("name"),
        _s("type"),
        _s("pct"),
        _s("pct_n"),
        _n("pct_i"),
        _s("bullet1"),
        _s("bullet2"),
        _s("bullet3"),
        _s("dollars"),
    ]
    answer = [
        _s("question_text"),
        _s("db_field"),
        _s("question_type"),
        _s("option_label"),
        _n("score"),
        _s("value"),
        _s("value_view"),
    ]
    macro = [_s("title"), _s("status"), _s("status_label"), _n("bar_pct"), _s("color"), _s("icon")]
    profile = [
        _s("name"),
        _s("label"),
        _s("description"),
        _n("min_score"),
        _n("max_score"),
        _n("equity_pct"),
        _n("alts_pct"),
        _n("cash_pct"),
    ]
    return [
        _s("client_full_name", required=True, nullable=False, label="Client name"),
        _s("client_email"),
        _s("lang", default="en"),
        _s("recommended_strategy", label="Investment profile"),
        _s("risk_profile", label="Investment label"),
        _s("suitability_score"),
        _s("created_at"),
        _b("use_default_model", default=True),
        _n("equity_pct"),
        _n("fixed_income_pct"),
        _n("alternatives_pct"),
        _n("cash_pct"),
        _s("equity_pct_view"),
        _s("fixed_income_pct_view"),
        _s("alternatives_pct_view"),
        _s("cash_pct_view"),
        {"key": "suitability_profile", "type": "object", "nullable": True, "fields": profile},
        _objects("sleeves", sleeve),
        _objects("holdings", holding),
        _objects("answers", answer),
        _objects("macro_outlook", macro),
        {
            "key": "TotalCurrency",
            "type": "derived",
            "expression": 'answers|find:"db_field","q1_investment_amount"|get:"value_view"',
        },
        {"key": "Palette", "type": "derived", "expression": json.dumps(PALETTE)},
        {"key": "SleevesSorted", "type": "derived", "expression": 'sleeves|sort_desc:"allocation_pct"'},
        {
            "key": "FixedIncomeHoldings",
            "type": "derived",
            "expression": 'holdings|reject:"id",(sleeves|map:"equity_profiles_id")|sort_desc:"pct_i"',
        },
    ]
