"""Calculate ideal equal-tempered fret positions and a uniform-spacing comparison."""

import argparse
import json
from math import isclose, isfinite, log2

SEMITONES = 12
OPEN_HZ = 110.0
MAX_FRET = 24


def fret_rows(scale):
    rows = []
    previous = 0.0
    for fret in range(MAX_FRET + 1):
        sounding_length = scale * 2 ** (-fret / SEMITONES)
        position = scale - sounding_length
        ratio = scale / sounding_length
        assert isclose(1200 * log2(ratio), 100 * fret, abs_tol=1e-9)
        rows.append({
            "fret": fret,
            "position_mm": position,
            "remaining_mm": sounding_length,
            "previous_gap_mm": position - previous,
            "frequency_hz": OPEN_HZ * ratio,
        })
        previous = position
    assert isclose(rows[12]["position_mm"], scale / 2)
    assert isclose(rows[24]["remaining_mm"], scale / 4)
    assert rows[13]["previous_gap_mm"] < rows[1]["previous_gap_mm"]
    assert isclose(rows[13]["previous_gap_mm"], rows[1]["previous_gap_mm"] / 2)
    return rows


def uniform_rows(scale):
    rows = []
    for fret in range(SEMITONES + 1):
        position = scale / 2 * (fret / SEMITONES)
        ratio = scale / (scale - position)
        cents = 1200 * log2(ratio)
        rows.append({
            "fret": fret,
            "position_mm": position,
            "cents_above_open": cents,
            "error_cents": cents - fret * 100,
        })
    assert rows[0]["error_cents"] == rows[12]["error_cents"] == 0
    assert all(row["error_cents"] < 0 for row in rows[1:12])
    return rows


def show_figure(path, scale, fretboard, uniform):
    from PIL import Image, ImageDraw, ImageFont

    image = Image.new("RGB", (1180, 500), "#ffffff")
    draw = ImageDraw.Draw(image)
    ink = "#183041"
    blue = "#146a94"
    orange = "#a44d26"

    def label(x, y, words, size, color=ink, anchor="mm"):
        font = ImageFont.load_default(size=size)
        draw.text((x, y), words, font=font, fill=color, anchor=anchor)

    def x_position(value):
        return 96 + 992 * (value / (scale / 2))

    label(590, 40, "Two ways to place 12 frets", 36)
    label(590, 83, f"Both start at the nut and end at {scale / 2:g} mm", 22)
    for y, rows, name, color in (
        (190, fretboard[:13], "Equal temperament", blue),
        (343, uniform, "Equal millimetre gaps", orange),
    ):
        label(96, y - 52, name, 25, color, "lm")
        draw.line((96, y, 1088, y), fill="#bec9d0", width=4)
        for row in rows:
            x = x_position(row["position_mm"])
            number = row["fret"]
            draw.line((x, y - 24, x, y + 24), fill=color, width=4)
            if number in (1, 3, 5, 7, 9, 12):
                label(x, y + 47, str(number), 20)
    label(96, 430, "0  (nut)", 20, anchor="lm")
    label(1088, 430, f"{scale / 2:g} mm  (fret 12)", 20, anchor="rm")
    label(590, 471, "Distance from the nut", 21)
    image.save(path)


def round_rows(rows):
    return [
        {key: round(value, 6) if isinstance(value, float) else value for key, value in row.items()}
        for row in rows
    ]


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--scale", type=float, default=648.0, help="nominal scale length in mm")
    parser.add_argument("--figure", metavar="PNG", help="generate a comparison diagram with Pillow")
    args = parser.parse_args()
    scale = args.scale
    if not isfinite(scale) or scale <= 4:
        parser.error("--scale must be finite and greater than 4 mm for the 1 mm offset check")

    fretboard = fret_rows(scale)
    uniform = uniform_rows(scale)
    sensitivity = []
    for fret in (1, 12, 24):
        length = fretboard[fret]["remaining_mm"]
        error = 1200 * log2(length / (length - 1))
        sensitivity.append({"fret": fret, "error_cents_for_1_mm_toward_bridge": error})

    if args.figure:
        show_figure(args.figure, scale, fretboard, uniform)
    print(json.dumps({
        "scale_mm": scale,
        "assumed_open_frequency_hz": OPEN_HZ,
        "one_semitone_frequency_ratio": round(2 ** (1 / SEMITONES), 9),
        "equal_temperament": round_rows(fretboard),
        "equal_mm_through_fret_12": round_rows(uniform),
        "position_error_examples": round_rows(sensitivity),
        "illustrative_error_cents_for_one_percent_more_tension": round(600 * log2(1.01), 6),
    }, indent=2, allow_nan=False))


if __name__ == "__main__":
    main()
