"""Golden geometry shared with the editor (``spec/fixtures/chart.fixtures.json``), read by pytest and vitest.

Regenerate after an intentional, reviewed geometry change::

    python -m snapfile_render.tools.chart_fixtures --update
"""

from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path
from typing import Any

from ..charts import chart_ops

FIXTURES = Path(__file__).resolve().parents[3] / "spec" / "fixtures" / "chart.fixtures.json"

LONG = "Очень длинное название категории, которое никуда не помещается"
CATS = ["Q1", "Q2", "Q3", "Q4"]
TWO = [{"name": "Equity", "values": [40, 55, 48, 62]}, {"name": "Bonds", "values": [25, 20, 32, 28]}]
NEG = [{"name": "Up", "values": [40, -25, 30, -10]}, {"name": "Down", "values": [-15, 10, -20, 25]}]
SEGMENTS = [
    {"pct": 50, "label": "Equity"},
    {"pct": 30, "label": "Bonds"},
    {"pct": 15, "label": "Alt"},
    {"pct": 5, "label": "Cash"},
]
CARTESIAN = ["bar", "barStacked", "barHorizontal", "barHorizontalStacked", "line", "area", "scatter"]


def _cases() -> list[dict[str, Any]]:
    out: list[dict[str, Any]] = []

    def add(case_id: str, kind: str, w: float = 320, h: float = 200, **rest: Any) -> None:
        out.append({"id": case_id, "input": {"chartType": kind, "w": w, "h": h, **rest}})

    for kind in [*CARTESIAN, "radar"]:
        add(f"{kind}-basic", kind, categories=CATS, series=TWO)
        add(f"{kind}-legend-labels", kind, categories=CATS, series=TWO, legend={"show": True}, labels={"show": True})
        add(
            f"{kind}-negative",
            kind,
            categories=CATS,
            series=NEG,
            labels={"show": True},
            legend={"show": True, "position": "top"},
        )
        add(f"{kind}-empty", kind, categories=[], series=[])
        add(f"{kind}-single", kind, categories=["One"], series=[{"values": [42]}], labels={"show": True})
        add(
            f"{kind}-long",
            kind,
            categories=[LONG, f"{LONG} 2", "Short"],
            series=[{"name": LONG, "values": [1200000, 850000.5, 420000]}],
            labels={"show": True},
            legend={"show": True},
            locale="ru",
        )
        add(f"{kind}-tiny", kind, w=30, h=20, categories=CATS, series=TWO, labels={"show": True}, legend={"show": True})
        add(
            f"{kind}-gaps",
            kind,
            categories=CATS,
            series=[{"values": [1, None, 3, 4]}, {"values": [None, 2, None, None]}],
        )
        add(
            f"{kind}-range",
            kind,
            categories=CATS,
            series=TWO,
            axes={"min": 30, "max": 50, "tickCount": 3},
            grid={"show": False},
        )
    for pos in ("left", "right", "top", "bottom"):
        add(f"bar-legend-{pos}", "bar", categories=CATS, series=TWO, legend={"show": True, "position": pos})
        add(f"pie-legend-{pos}", "pie", segments=SEGMENTS, legend={"show": True, "position": pos})
    add(
        "bar-many-categories",
        "bar",
        w=200,
        h=120,
        categories=[f"Category {i}" for i in range(30)],
        series=[{"values": list(range(30))}],
    )
    add(
        "barHorizontal-many",
        "barHorizontal",
        w=200,
        h=120,
        categories=[f"Category {i}" for i in range(30)],
        series=[{"values": list(range(30))}],
    )
    add(
        "bar-options",
        "bar",
        categories=CATS,
        series=TWO,
        barGap=0.6,
        palette=["#111111", "#222222"],
        labels={"show": True, "fontSize": 9, "fontWeight": 700, "decimals": 1, "prefix": "$", "suffix": "k"},
    )
    add(
        "bar-point-colors",
        "bar",
        categories=CATS,
        series=[{"values": [1, 2, 3, 4], "colors": ["#FF0000", None, "#00FF00", None], "color": "#0000FF"}],
    )
    add("bar-no-axes", "bar", categories=CATS, series=TWO, axes={"show": False}, grid={"show": False})
    add("bar-not-nice", "bar", categories=CATS, series=TWO, axes={"nice": False, "tickCount": 4})
    add(
        "bar-small-values",
        "bar",
        categories=CATS,
        series=[{"values": [0.012, 0.034, 0.021, 0.008]}],
        labels={"show": True, "decimals": 3},
    )
    add(
        "bar-big-values", "bar", categories=CATS, series=[{"values": [1e12, 2.5e12, 7e11, 3e12]}], labels={"show": True}
    )
    add(
        "line-smooth",
        "line",
        categories=["a", "b", "c", "d", "e", "f"],
        series=[{"values": [1, 9, 2, 8, 3, 7]}],
        smooth=True,
        lineWidth=1.5,
        markers={"show": False},
    )
    add(
        "area-smooth",
        "area",
        categories=["a", "b", "c", "d", "e", "f"],
        series=[{"values": [1, 9, 2, 8, 3, 7]}],
        smooth=True,
        fillOpacity=0.5,
    )
    add("line-markers", "line", categories=CATS, series=TWO, markers={"size": 10})
    add(
        "scatter-xs",
        "scatter",
        categories=[],
        series=[
            {"name": "A", "values": [1, 5, 3], "xs": [10, 20, 30]},
            {"name": "B", "values": [2, 4, 6], "xs": [15, None, 45]},
        ],
    )
    add("scatter-x-range", "scatter", series=[{"values": [1, 5, 3], "xs": [10, 20, 30]}], axes={"xMin": 15, "xMax": 25})
    add("radar-two", "radar", categories=["A", "B"], series=[{"values": [1, 2]}])
    add(
        "radar-start",
        "radar",
        categories=["A", "B", "C", "D", "E"],
        series=TWO,
        startAngle=36,
        markers={"show": False},
        fillOpacity=0.1,
    )
    add("pie-basic", "pie", segments=SEGMENTS)
    add("pie-remainder", "pie", segments=[{"pct": 60, "label": "A"}], remainderColor="#ABCDEF")
    add("pie-over-100", "pie", segments=[{"pct": 150, "label": "A"}, {"pct": 50, "label": "B"}])
    add(
        "pie-normalize",
        "pie",
        segments=[{"pct": 3, "label": "A"}, {"pct": 5, "label": "B"}, {"pct": 2, "label": "C"}],
        normalize=True,
    )
    add("pie-full", "pie", segments=[{"pct": 100, "label": "A"}])
    add("pie-empty", "pie", segments=[])
    add("pie-negative", "pie", segments=[{"pct": -5, "label": "A"}, {"pct": 40, "label": "B"}])
    add("pie-start-radii", "pie", segments=SEGMENTS, startAngle=45, outerRadius=70, innerRadius=20)
    add("pie-no-labels", "pie", segments=SEGMENTS, labels={"show": False})
    add("pie-small-slice-wide", "pie", w=100, h=100, segments=[{"pct": 90}, {"pct": 10}])
    add("donut-legend", "donut", segments=SEGMENTS, legend={"show": True, "position": "right"})
    return out


def build() -> dict[str, Any]:
    cases = _cases()
    for case in cases:
        case["expected"] = chart_ops(case["input"])
    return {
        "version": 1,
        "algorithm": "spec/scene-additions.md §1a",
        "tolerance": {"position_pt": 0.01, "text": "exact"},
        "cases": cases,
    }


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--update", action="store_true")
    args = parser.parse_args()
    data = build()
    text = json.dumps(data, ensure_ascii=False, indent=1) + "\n"
    if args.update:
        FIXTURES.write_text(text, encoding="utf-8")
        print(f"wrote {len(data['cases'])} cases to {FIXTURES}")
        return 0
    if not FIXTURES.exists() or json.loads(FIXTURES.read_text(encoding="utf-8")) != json.loads(text):
        print("chart fixtures are out of date", file=sys.stderr)
        return 1
    print(f"{len(data['cases'])} cases match")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
