"""A-series folds and centered print geometry; no printer access."""
import argparse
import json
import platform
import sys
from decimal import Decimal, localcontext
from fractions import Fraction
from pathlib import Path

A3, A4, A5 = (297, 420), (210, 297), (148, 210)
LETTER = (Fraction("215.9"), Fraction("279.4"))


def fold(size):
    """Cut across the long side, then return short and long sides."""
    short, long = sorted(map(Fraction, size))
    return tuple(sorted((short, long / 2)))


def printable(size, margin):
    """Teaching model: identical margins on all four sides."""
    inner = tuple(Fraction(side) - 2 * margin for side in size)
    if margin < 0 or min(inner) <= 0:
        raise ValueError("margins must leave a positive printable rectangle")
    return inner


def fit(source, target):
    return min(Fraction(t) / Fraction(s) for s, t in zip(source, target))


def decimal(value):
    if isinstance(value, Fraction):
        return Decimal(value.numerator) / Decimal(value.denominator)
    return Decimal(value)


def mm(value):
    return format(decimal(value), ".8f")


def scenario(name, source, target, scale):
    src = tuple(map(decimal, source))
    dst = tuple(map(decimal, target))
    # Exact rational arithmetic for all cases except the irrational ideal scale.
    dims = tuple(s * scale for s in (
        map(decimal, source) if isinstance(scale, Decimal) else map(Fraction, source)
    ))
    fits = all(d <= t for d, t in zip(dims, dst if isinstance(scale, Decimal) else target))
    return {
        "name": name, "source_mm": list(map(mm, src)), "target_mm": list(map(mm, dst)),
        "scale_percent": mm(scale * 100), "scaled_mm": list(map(mm, dims)),
        "target_minus_scaled_mm": [mm(t - decimal(d)) for d, t in zip(dims, dst)],
        "fits": fits,
    }


def run():
    inner = printable(A3, 5)
    art = (190, 277)
    sqrt2 = Decimal(2).sqrt()
    p141, p70 = Fraction(141, 100), Fraction(70, 100)
    assert fold(A3) == A4
    assert fold(A4) == (Fraction(297, 2), 210) and fold(A4) != A5
    assert fold((100, 300)) == (100, 150)  # Folding need not swap the axes.
    assert inner == (287, 410)
    assert fit(A4, A3) == Fraction(140, 99)
    assert fit(A3, A4) == Fraction(70, 99)
    assert fit(A4, inner) == Fraction(41, 30)
    assert p141 * p70 == Fraction(987, 1000)
    gutter = 6
    two_up_width = 2 * A4[0] + gutter
    two_up_scale = min(Fraction(A3[1] - gutter, 2 * A4[0]), Fraction(A3[0], A4[1]))
    assert two_up_width == 426 > A3[1]
    assert two_up_scale == Fraction(69, 70)
    assert 2 * A4[0] * two_up_scale + gutter == A3[1]
    assert A4[1] * two_up_scale <= A3[0]
    for bad in (-1, 149):
        try:
            printable(A3, bad)
        except ValueError:
            pass
        else:
            raise AssertionError("invalid margin accepted")
    cases = [
        ("a4_to_a3_nominal_fit", A4, A3, fit(A4, A3)),
        ("a4_to_a3_ideal_sqrt2", A4, A3, sqrt2),
        ("a4_to_a3_141", A4, A3, p141),
        ("a4_to_a3_200", A4, A3, Fraction(2)),
        ("a3_to_a4_nominal_fit", A3, A4, fit(A3, A4)),
        ("a3_to_a4_70", A3, A4, p70),
        ("a4_to_a3_with_5mm_margins_fit", A4, inner, fit(A4, inner)),
        ("a4_to_a3_with_5mm_margins_141", A4, inner, p141),
        ("a4_artwork_to_a3_with_5mm_margins_141", art, inner, p141),
        ("a4_to_letter_nominal_fit", A4, LETTER, fit(A4, LETTER)),
    ]
    results = [scenario(*c) for c in cases]
    assert [c["fits"] for c in results] == [
        True, False, True, False, True, True, True, False, True, True,
    ]
    assert results[7]["target_minus_scaled_mm"] == ["-9.10000000", "-8.77000000"]
    assert results[8]["scaled_mm"] == ["267.90000000", "390.57000000"]
    return {
        "environment": {
            "os": platform.system(), "os_version": platform.mac_ver()[0] or platform.release(),
            "machine": platform.machine(), "python": sys.version.split()[0],
        },
        "folded_a3_mm": list(map(mm, fold(A3))),
        "folded_a4_mm": list(map(mm, fold(A4))),
        "a5_nominal_mm": list(A5),
        "a4_long_over_short": mm(Fraction(297, 210)),
        "a3_long_over_short": mm(Fraction(420, 297)),
        "ideal_long_over_short": mm(sqrt2),
        "length_after_141_then_70_percent_of_original": mm(p141 * p70 * 100),
        "two_up_on_landscape_a3": {
            "fixed_gutter_mm": gutter, "unscaled_pair_width_mm": two_up_width,
            "nominal_max_scale_percent": mm(two_up_scale * 100),
        },
        "scenarios": results,
    }


def svg(report):
    left_scale = Decimal(".70")
    right_scale = Decimal(".62")
    lw, lh = [decimal(x) * left_scale for x in reversed(A3)]
    full_w, full_h = [decimal(x) * right_scale for x in A3]
    area_w, area_h = [decimal(x) * right_scale for x in printable(A3, 5)]
    art_w, art_h = [Decimal(x) * right_scale for x in report["scenarios"][8]["scaled_mm"]]
    cx, cy = Decimal(715), Decimal(225)
    def rect(w, h, cls):
        return (f'<rect x="{cx-w/2:.4f}" y="{cy-h/2:.4f}" '
                f'width="{w:.4f}" height="{h:.4f}" class="{cls}"/>')
    return f'''<svg xmlns="http://www.w3.org/2000/svg" width="960" height="455" viewBox="0 0 960 455" role="img" aria-labelledby="title desc">
<title id="title">A3 folding and printable area</title>
<desc id="desc">An A3 landscape sheet divides into two nominal A4 portraits. On the right, centered artwork fits within a hypothetical A3 printable area even when the full scaled page does not.</desc>
<style>
text{{font-family:system-ui,sans-serif;fill:#102841}}.head{{font-size:25px;font-weight:700}}.body{{font-size:19px}}.label{{font-size:22px;font-weight:700;text-anchor:middle}}.small{{font-size:17px;fill:#304e69}}.paper{{fill:#fff;stroke:#263e53;stroke-width:2}}.area{{fill:#e0efff;stroke:#1263a5;stroke-width:1.7;stroke-dasharray:5 3}}.art{{fill:#c2ebdf;stroke:#007559;stroke-width:1.7}}
</style>
<rect width="960" height="455" fill="#fff"/>
<rect x="16" y="16" width="450" height="420" rx="14" fill="#f1f5f9"/>
<rect x="494" y="16" width="450" height="420" rx="14" fill="#f1f5f9"/>
<text x="40" y="57" class="head">01  Fold the sheet</text>
<text x="518" y="57" class="head">02  Fit the artwork</text>
<rect x="94" y="111" width="{lw}" height="{lh}" rx="0" fill="#e0efff" stroke="#263e53" stroke-width="2"/>
<rect x="{94+lw/2}" y="112" width="{lw/2-1}" height="{lh-2}" fill="#c2ebdf"/>
<path d="M {94+lw/2} 111 v {lh}" fill="none" stroke="#102841" stroke-width="2" stroke-dasharray="7 5"/>
<text x="{94+lw/4}" y="212" class="label">A4</text>
<text x="{94+lw*3/4}" y="212" class="label">A4</text>
<text x="{94+lw/4}" y="240" class="small" text-anchor="middle">210 × 297</text>
<text x="{94+lw*3/4}" y="240" class="small" text-anchor="middle">210 × 297</text>
<text x="40" y="361" class="body">A3 sheet: 420 × 297 mm</text>
<text x="40" y="391" class="small">Fold along the dotted line.</text>
{rect(full_w,full_h,"paper")}
{rect(area_w,area_h,"area")}
{rect(art_w,art_h,"art")}
<text x="715" y="219" class="label">141% artwork</text>
<text x="715" y="246" class="small" text-anchor="middle">267.90 × 390.57</text>
<text x="518" y="386" class="body">Dashed area: 287 × 410 mm</text>
<text x="518" y="412" class="small">A3 with modeled 5 mm margins</text>
</svg>
'''


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--svg", type=Path, help="also write the original diagram")
    args = parser.parse_args()
    with localcontext() as context:
        context.prec = 50
        report = run()
        if args.svg:
            args.svg.write_text(svg(report), encoding="utf-8")
        print(json.dumps(report, ensure_ascii=False, indent=2))
