"""Audit every `@media (color-gamut: p3)` colour rule on the live site against the real gamut edges.

For each rule: the chroma the sRGB rule asks for, the chroma the P3 rule asks for, and the largest
chroma sRGB and Display P3 can hold at that lightness and hue. Then a proposed value that follows the
post's own rule ("the sRGB rule is finished; the P3 rule only adds chroma sRGB cannot hold, capped
per hue at the P3 edge"):

    proposed sRGB chroma = min(sRGB rule chroma, 0.98 x sRGB edge)
    proposed P3 chroma   = min(P3 rule chroma, 0.98 x P3 edge), kept only when it lies beyond the sRGB
                           edge and at least 0.005 above the sRGB value
    (the 2% margin keeps OKLab blends between neighbouring colours from grazing past the edge)

A P3 rule whose colour fits inside sRGB is not a wider colour, only a different one for P3 viewers, so
it is dropped (or, by choice, moved into the base rule so every screen gets it).

No dependencies (pure Python). Run: python3 scripts/site_p3_audit.py  ->  data/site_p3_audit.json
Rule values were read from fauzul-personal/src/styles (tokens.css, paper-hero.css,
paper-industries.css) and src/components/paper/industries/scenes/*.tsx on 2026-10-28.
"""

import json
import math
from pathlib import Path


def oklch_to_linear(lightness, chroma, hue, space):
    a = chroma * math.cos(math.radians(hue))
    b = chroma * math.sin(math.radians(hue))
    l_ = (lightness + 0.3963377774 * a + 0.2158037573 * b) ** 3
    m_ = (lightness - 0.1055613458 * a - 0.0638541728 * b) ** 3
    s_ = (lightness - 0.0894841775 * a - 1.2914855480 * b) ** 3
    x = 1.2270138511 * l_ - 0.5577999807 * m_ + 0.2812561490 * s_
    y = -0.0405801784 * l_ + 1.1122568696 * m_ - 0.0716766787 * s_
    z = -0.0763812845 * l_ - 0.4214819784 * m_ + 1.5861632204 * s_
    if space == "srgb":
        return (3.2409699419 * x - 1.5373831776 * y - 0.4986107603 * z,
                -0.9692436363 * x + 1.8759675015 * y + 0.0415550574 * z,
                0.0556300797 * x - 0.2039769589 * y + 1.0569715142 * z)
    return (2.4934969119 * x - 0.9313836179 * y - 0.4027107845 * z,
            -0.8294889696 * x + 1.7626640603 * y + 0.0236246858 * z,
            0.0358458302 * x - 0.0761723893 * y + 0.9568845240 * z)


def in_gamut(lightness, chroma, hue, space, tolerance=1e-4):
    return all(-tolerance <= channel <= 1 + tolerance for channel in oklch_to_linear(lightness, chroma, hue, space))


def gamut_edge(lightness, hue, space):
    low, high = 0.0, 0.5
    for _ in range(40):
        middle = (low + high) / 2
        if in_gamut(lightness, middle, hue, space):
            low = middle
        else:
            high = middle
    return low


def check_against_published_findings():
    # F1 and F5 in sources.md were computed with colour-science; this pure version must agree.
    expected = [(0.84, 145, "srgb", 0.264), (0.84, 145, "p3", 0.359), (0.84, 265, "srgb", 0.079),
                (0.84, 265, "p3", 0.086), (0.398, 277, "srgb", 0.246), (0.398, 277, "p3", 0.249)]
    for lightness, hue, space, value in expected:
        found = gamut_edge(lightness, hue, space)
        assert abs(found - value) < 0.0015, (lightness, hue, space, found, value)


EDGE_MARGIN = 0.98

INDUSTRY_HUES = {  # oklchHue, chroma from the scene files
    "gaming": (30, 0.15), "hue-52": (52, 0.19), "food": (80, 0.17), "trade": (98, 0.11),
    "hue-128": (128, 0.16), "health": (190, 0.15), "hue-220": (220, 0.17), "media": (250, 0.15),
}


def rules():
    yield ("tokens.css", "--indigo", 0.398, 0.18, 0.215, 277, 1.0)
    yield ("tokens.css", "--indigo-deep", 0.357, 0.178, 0.20, 275, 1.0)
    yield ("paper-hero.css", "--hero-violet", 0.516, 0.221, 0.25, 281.3, 1.0)
    yield ("paper-hero.css", "--hero-violet-ring (alpha 0.15)", 0.516, 0.221, 0.25, 281.3, 0.15)
    yield ("paper-hero.css", "--hero-smoke (alpha 0.7)", 0.735, 0.122, 0.14, 290.6, 0.7)
    yield ("paper-hero.css", "--hero-indigo-wash (alpha 0.06)", 0.398, 0.18, 0.215, 277, 0.06)
    for name, (hue, scene_chroma) in INDUSTRY_HUES.items():
        yield ("paper-industries.css", f"--field-accent [{name}, h{hue}]", 0.62, 0.19, 0.22, hue, 1.0)
        # Marks: --saturation = 0.19 x boost; rest 1.12 -> P3 1.22, hover 1.26 -> P3 1.36.
        yield ("paper-industries.css", f"mark --accent-left rest [{name}]", 0.66, 0.19 * 1.12, 0.19 * 1.22, hue, 0.84)
        yield ("paper-industries.css", f"mark --accent-left hover [{name}]", 0.66, 0.19 * 1.26, 0.19 * 1.36, hue, 0.84)
        yield ("paper-industries.css", f"scene --accent-left [{name}]", 0.66, scene_chroma, scene_chroma * 1.15, hue, 0.86)


def verdict(design_srgb, design_p3, srgb_edge, p3_edge):
    if design_p3 > p3_edge + 0.002:
        return "P3 rule exceeds P3: clipped even on P3 screens"
    if design_p3 <= srgb_edge + 0.002:
        return "P3 rule fits inside sRGB: not a gamut gain, just a different colour for P3 viewers"
    return "P3 rule uses real P3 headroom"


def main():
    check_against_published_findings()
    rows = []
    for file, name, lightness, design_srgb, design_p3, hue, alpha in rules():
        srgb_edge = gamut_edge(lightness, hue, "srgb")
        p3_edge = gamut_edge(lightness, hue, "p3")
        # 2% inside each edge, so blends between neighbouring colours do not graze past it.
        proposed_srgb = min(design_srgb, EDGE_MARGIN * srgb_edge)
        proposed_p3 = min(design_p3, EDGE_MARGIN * p3_edge)
        # A P3 rule earns its place only when it asks for colour sRGB cannot hold, by a visible margin.
        keep_p3_rule = proposed_p3 > srgb_edge and proposed_p3 - proposed_srgb >= 0.005
        rows.append({
            "file": file, "rule": name, "lightness": lightness, "hue": hue, "alpha": alpha,
            "srgb_rule_chroma": round(design_srgb, 4), "p3_rule_chroma": round(design_p3, 4),
            "srgb_edge": round(srgb_edge, 4), "p3_edge": round(p3_edge, 4),
            "srgb_rule_clipped_on_srgb": design_srgb > srgb_edge + 0.002,
            "verdict": verdict(design_srgb, design_p3, srgb_edge, p3_edge),
            "proposed_srgb_chroma": round(proposed_srgb, 3),
            "proposed_p3_chroma": round(proposed_p3, 3) if keep_p3_rule else None,
            # Rough visible gain once composited: alpha x the chroma P3 adds over the sRGB colour.
            "composited_gain": round(alpha * (proposed_p3 - proposed_srgb), 4) if keep_p3_rule else 0.0,
        })
    output = Path(__file__).resolve().parent.parent / "data" / "site_p3_audit.json"
    output.write_text(json.dumps(rows, indent=2))
    for row in rows:
        print(f"{row['rule']:<44} L{row['lightness']:<5} h{row['hue']:<6} sRGB-rule {row['srgb_rule_chroma']:<6} "
              f"P3-rule {row['p3_rule_chroma']:<6} edges {row['srgb_edge']}/{row['p3_edge']}  "
              f"-> {row['proposed_srgb_chroma']} / {row['proposed_p3_chroma']}  [{row['verdict']}]"
              f"{'  (sRGB rule clipped)' if row['srgb_rule_clipped_on_srgb'] else ''}")


if __name__ == "__main__":
    main()
