"""KP-17: a 17-page A4-landscape commercial proposal similar to the customer's current document.

Composition: cover with photo; intro letter; portfolio allocation (donut charts + 12-row table repeater);
Market Outlook flow repeater with 40 rows (4 pages, repeated header); 7 content pages (2 columns of text,
bars, a second photo on one of them); disclaimers; contacts. Page numbers "N / total" on every page except
the cover. Fonts: Inter 400/500/600/700 (+italic). Vector shapes instead of SVG (SVG nodes: iteration 2).
"""

from __future__ import annotations

import io
import random
from typing import Any

from PIL import Image, ImageDraw, ImageFilter

W, H = 841.89, 595.28
TEAL, LIME, INK, GREY = "#0F5470", "#3CCB4A", "#1C2B48", "#7A828C"

LOREM_EN = (
    "Our investment committee reviews the portfolio every quarter and rebalances positions when allocations drift "
    "beyond the agreed tolerance. We focus on diversified, liquid instruments with transparent fees and a clear "
    "role in the plan, so that every position contributes to the long-term objective you have defined with us. "
)
LOREM_RU = (
    "Мы подготовили для вас персональное инвестиционное предложение с учётом профиля риска, горизонта "
    "инвестирования и ваших финансовых целей. Портфель пересматривается ежеквартально, а отклонения от целевой "
    "структуры корректируются в рамках согласованных допусков. "
)


def photo_jpeg(seed: int, size: tuple[int, int] = (1600, 1000)) -> bytes:
    rnd = random.Random(seed)
    img = Image.new("RGB", size, (30, 90, 120))
    d = ImageDraw.Draw(img)
    for _ in range(140):
        x, y = rnd.randrange(size[0]), rnd.randrange(size[1])
        r = rnd.randrange(40, 260)
        c = (rnd.randrange(40, 200), rnd.randrange(100, 220), rnd.randrange(90, 200))
        d.ellipse((x - r, y - r, x + r, y + r), fill=c)
    img = img.filter(ImageFilter.GaussianBlur(18))
    buf = io.BytesIO()
    img.save(buf, "JPEG", quality=85)
    return buf.getvalue()


def _t(
    node_id: str,
    text: str,
    x: float,
    y: float,
    w: float,
    h: float,
    *,
    size: float = 9,
    weight: int = 400,
    color: str = INK,
    align: str = "left",
    **kw: Any,
) -> dict[str, Any]:
    return {
        "id": node_id,
        "type": "text",
        "x": x,
        "y": y,
        "w": w,
        "h": h,
        "content": [
            {
                "align": align,
                "runs": [{"text": text, "style": {"fontSize": size, "fontWeight": weight, "color": color}}],
            }
        ],
        **kw,
    }


def _chrome(title: str, idx: int) -> list[dict[str, Any]]:
    return [
        {
            "id": f"band{idx}",
            "type": "rect",
            "x": 0,
            "y": 0,
            "w": W,
            "h": 64,
            "fills": [
                {
                    "type": "linear",
                    "angle": 90,
                    "stops": [{"offset": 0, "color": "#2C8FB8"}, {"offset": 1, "color": TEAL}],
                }
            ],
        },
        _t(f"title{idx}", title, 40, 20, 600, 26, size=18, weight=700, color="#FFFFFF"),
        _t(f"brand{idx}", "ACCUVEST", 640, 24, 160, 16, size=9, weight=600, color="#FFFFFF", align="right"),
        {
            "id": f"foot{idx}",
            "type": "rect",
            "x": 0,
            "y": 560,
            "w": W,
            "h": 35.28,
            "fills": [{"type": "solid", "color": "#575757"}],
        },
        _t(f"site{idx}", "accuvest.com · {{client.full_name}}", 40, 572, 300, 12, size=7.5, color="#FFFFFF"),
        _t(
            f"pn{idx}",
            "{{page.number}} / {{page.total}}",
            700,
            572,
            101.89,
            12,
            size=7.5,
            color="#DDDDDD",
            align="right",
        ),
    ]


def _content_sheet(i: int, photo: bool) -> dict[str, Any]:
    children = _chrome(f"Section {i}: {'Strategy' if i % 2 else 'Risk management'}", i)
    children += [
        _t(
            f"lead{i}",
            "{{client.full_name}}, " + LOREM_EN[:140],
            40,
            84,
            760,
            30,
            size=12,
            weight=600,
            autoSize="height",
        ),
        _t(f"c1{i}", (LOREM_EN + LOREM_RU) * 2, 40, 130, 360, 260, size=8.5, align="justify", overflowMode="ellipsis"),
        _t(
            f"c2{i}",
            (LOREM_RU + LOREM_EN) * 2,
            440,
            130,
            360,
            200 if photo else 260,
            size=8.5,
            align="justify",
            overflowMode="ellipsis",
        ),
    ]
    if photo:
        children.append(
            {
                "id": f"ph{i}",
                "type": "image",
                "x": 440,
                "y": 340,
                "w": 360,
                "h": 150,
                "assetId": "photo2",
                "fit": "cover",
                "cornerRadius": 8,
            }
        )
    for b in range(5):
        children += [
            _t(f"bl{i}-{b}", f"Indicator {b + 1}", 40, 410 + b * 26, 120, 12, size=8, weight=500),
            {
                "id": f"bt{i}-{b}",
                "type": "rect",
                "x": 170,
                "y": 412 + b * 26,
                "w": 220,
                "h": 8,
                "fills": [{"type": "solid", "color": "#E7ECEF"}],
            },
            {
                "id": f"bb{i}-{b}",
                "type": "rect",
                "x": 170,
                "y": 412 + b * 26,
                "w": 40 + 35 * b,
                "h": 8,
                "fills": [{"type": "solid", "color": LIME if b % 2 else "#2A8BD8"}],
            },
        ]
    return {
        "id": f"content{i}",
        "name": f"Content {i}",
        "format": "A4",
        "orientation": "landscape",
        "children": children,
    }


def build_kp17() -> tuple[dict[str, Any], dict[str, Any]]:
    sheets: list[dict[str, Any]] = []
    sheets.append(
        {
            "id": "cover",
            "name": "Cover",
            "format": "A4",
            "orientation": "landscape",
            "pageNumbering": {"skip": True},
            "children": [
                {
                    "id": "cv-img",
                    "type": "image",
                    "x": 0,
                    "y": 0,
                    "w": 300,
                    "h": H,
                    "assetId": "photo1",
                    "fit": "cover",
                },
                {
                    "id": "cv-band",
                    "type": "rect",
                    "x": 0,
                    "y": 100,
                    "w": W,
                    "h": 78,
                    "fills": [{"type": "solid", "color": TEAL}],
                },
                _t(
                    "cv-tag",
                    "YOUR FUTURE  AWAITS",
                    320,
                    126,
                    500,
                    26,
                    size=18,
                    weight=700,
                    color="#E3A43B",
                    align="center",
                ),
                _t(
                    "cv-name",
                    "{{client.full_name}}",
                    336,
                    252,
                    470,
                    34,
                    size=26,
                    weight=700,
                    color="#164E70",
                    autoSize="height",
                ),
                _t(
                    "cv-risk",
                    "{{risk_profile.name}}",
                    336,
                    300,
                    470,
                    24,
                    size=17,
                    weight=700,
                    color="#E8742A",
                    pushDown=True,
                    autoSize="height",
                ),
                _t(
                    "cv-date",
                    'Prepared {{deal.date|date:"MMMM d, yyyy"}} · {{deal.amount|money:"USD"}}',
                    336,
                    340,
                    470,
                    14,
                    size=9,
                    color=GREY,
                    pushDown=True,
                ),
            ],
        }
    )
    letter = _chrome("Personal letter", 1)
    letter += [
        _t(
            "letter",
            (
                "Dear {{client.full_name}},\n\n"
                + LOREM_EN * 3
                + "\n\n"
                + LOREM_RU * 3
                + "\n\nSincerely,\n{{advisor.name}}"
            ),
            80,
            90,
            680,
            440,
            size=10,
            align="justify",
            overflowMode="shrink",
            minFontSize=7,
        )
    ]
    sheets.append({"id": "letter", "name": "Letter", "format": "A4", "orientation": "landscape", "children": letter})
    alloc = _chrome("Portfolio allocation", 2)
    for k, (start, end, color) in enumerate(
        [(-90, 30, "#2A8BD8"), (30, 140, LIME), (140, 230, "#E3A43B"), (230, 270, "#C23B7A")]
    ):
        alloc.append(
            {
                "id": f"arc{k}",
                "type": "ellipse",
                "x": 60,
                "y": 110,
                "w": 220,
                "h": 220,
                "arc": {"start": start, "end": end, "innerRatio": 0.62},
                "fills": [{"type": "solid", "color": color}],
            }
        )
    alloc.append(
        _t(
            "alloc-total",
            '{{portfolio.items|sum:"weight"|percent}}',
            120,
            208,
            100,
            24,
            size=18,
            weight=700,
            align="center",
        )
    )
    alloc.append(
        {
            "id": "alloc-table",
            "type": "repeater",
            "x": 340,
            "y": 100,
            "w": 460,
            "h": 440,
            "source": "portfolio.items",
            "as": "it",
            "gap": 4,
            "header": {
                "h": 22,
                "children": [
                    _t("ah1", "Instrument", 0, 4, 200, 12, size=8, weight=600, color=GREY),
                    _t("ah2", "Weight", 260, 4, 80, 12, size=8, weight=600, color=GREY, align="right"),
                    _t("ah3", "Amount", 360, 4, 100, 12, size=8, weight=600, color=GREY, align="right"),
                ],
            },
            "item": {
                "h": 26,
                "children": [
                    {
                        "id": "arow",
                        "type": "rect",
                        "x": 0,
                        "y": 0,
                        "w": 460,
                        "h": 26,
                        "fills": [{"type": "solid", "color": "#F5F7F8"}],
                    },
                    _t("a1", "{{it.title}}", 8, 7, 240, 12, size=9, weight=500, overflowMode="ellipsis"),
                    _t("a2", "{{it.weight|percent:1}}", 260, 7, 80, 12, size=9, align="right"),
                    _t("a3", '{{it.amount|money:"USD"}}', 350, 7, 102, 12, size=9, align="right"),
                ],
            },
        }
    )
    sheets.append({"id": "alloc", "name": "Allocation", "format": "A4", "orientation": "landscape", "children": alloc})
    outlook = _chrome("Market outlook", 3)
    outlook.append(
        {
            "id": "factors",
            "type": "repeater",
            "x": 120,
            "y": 90,
            "w": 600,
            "h": 450,
            "source": "outlook",
            "as": "f",
            "gap": 6,
            "overflow": "nextPage",
            "header": {
                "h": 20,
                "repeat": True,
                "children": [
                    _t("fh1", "FACTOR", 30, 4, 200, 12, size=7, weight=600, color=GREY),
                    _t("fh2", "ASSESSMENT", 240, 4, 200, 12, size=7, weight=600, color=GREY),
                ],
            },
            "item": {
                "h": 24,
                "children": [
                    {
                        "id": "fi",
                        "type": "ellipse",
                        "x": 0,
                        "y": 2,
                        "w": 20,
                        "h": 20,
                        "fills": [{"type": "solid", "color": "#DDE9F2"}],
                    },
                    _t("ft", "{{f.title}}", 30, 6, 200, 12, size=9, weight=700, overflowMode="ellipsis"),
                    {
                        "id": "ftr",
                        "type": "rect",
                        "x": 240,
                        "y": 8,
                        "w": 250,
                        "h": 9,
                        "fills": [{"type": "solid", "color": "#E7ECEF"}],
                    },
                    {
                        "id": "fb",
                        "type": "rect",
                        "x": 240,
                        "y": 8,
                        "w": 250,
                        "h": 9,
                        "bind": {"w": "f.score * 2.5", "fills.0.color": "f.color"},
                        "fills": [{"type": "solid", "color": LIME}],
                    },
                    _t("fs", "{{f.status}}", 505, 6, 95, 12, size=8.5),
                ],
            },
        }
    )
    sheets.append(
        {
            "id": "outlook",
            "name": "Market outlook",
            "format": "A4",
            "orientation": "landscape",
            "overflow": {"continuationSheetId": "outlook", "maxPages": 10},
            "children": outlook,
        }
    )
    for i in range(4, 13):
        sheets.append(_content_sheet(i, photo=(i == 6)))
    disc = _chrome("Important information", 20)
    disc.append(
        _t(
            "disc",
            (LOREM_EN + LOREM_RU) * 6,
            40,
            84,
            760,
            460,
            size=7,
            align="justify",
            color=GREY,
            overflowMode="ellipsis",
        )
    )
    sheets.append({"id": "disc", "name": "Disclaimers", "format": "A4", "orientation": "landscape", "children": disc})
    contact = _chrome("Contacts", 21)
    contact += [
        _t(
            "ct",
            '{{advisor.name}}\n{{advisor.phone|phone:"+1 (###) ###-####"}}\n{{advisor.email}}',
            40,
            120,
            400,
            80,
            size=14,
            weight=500,
        )
    ]
    sheets.append(
        {"id": "contact", "name": "Contacts", "format": "A4", "orientation": "landscape", "children": contact}
    )
    doc = {
        "formatVersion": 1,
        "meta": {"title": "Proposal for {{client.full_name}}"},
        "defaults": {"fontFamily": "Inter", "fontSize": 9, "color": INK, "lineHeight": 1.3, "locale": "en"},
        "sheets": sheets,
    }
    rnd = random.Random(17)
    colors = ["#3CCB4A", "#F0302A", "#F2C01E"]
    data = {
        "client": {"full_name": "Andrey Sgurskiy"},
        "risk_profile": {"name": "Income + Growth Investor"},
        "deal": {"date": "2026-11-03", "amount": 1250000},
        "advisor": {"name": "Anna Petrova, CFA", "phone": "19259302882", "email": "a.petrova@accuvest.example"},
        "portfolio": {
            "items": [
                {
                    "title": f"Instrument {i + 1} — {'Bonds' if i % 2 else 'Equity'} fund",
                    "weight": round(1 / 12, 4),
                    "amount": 104166.67,
                }
                for i in range(12)
            ]
        },
        "outlook": [
            {
                "title": f"Factor {i + 1}: {'Economic growth' if i % 3 else 'Inflation & policy'}",
                "score": rnd.randrange(10, 100),
                "color": colors[i % 3],
                "status": ["Positive", "Cautious", "Neutral"][i % 3],
            }
            for i in range(40)
        ],
    }
    return doc, data
