"""Exact rational teaching model, not a file-format encoder or benchmark."""
import argparse
from fractions import Fraction as F
import json
from math import lcm
from pathlib import Path

MODEL = (3, 1)


def validate(weights):
    if len(weights) != 2 or any(type(w) is not int or w <= 0 for w in weights):
        raise ValueError("Expected two positive integer frequencies")


def interval(message, weights=MODEL):
    validate(weights)
    if not isinstance(message, str) or len(message) > 64 or set(message) - {"A", "B"}:
        raise ValueError("Expected at most 64 A/B symbols")
    split = F(weights[0], sum(weights))
    low, high = F(0), F(1)
    for symbol in message:
        middle = low + (high - low) * split
        if symbol == "A":
            high = middle
        else:
            low = middle
    return low, high


def shortest_prefix(low, high):
    if not F(0) <= low < high <= F(1):
        raise ValueError("Expected a nonempty interval within [0,1)")
    for bits in range(1025):
        scale = 1 << bits
        scaled = low * scale
        integer = -(-scaled.numerator // scaled.denominator)
        if F(integer + 1, scale) <= high:
            return (format(integer, "0" + str(bits) + "b") if bits else "",
                    F(integer, scale), F(integer + 1, scale))
    raise ValueError("Teaching-model bit limit exceeded")


def decode(tag, length, weights=MODEL):
    validate(weights)
    if type(length) is not int or not 0 <= length <= 64 or not F(0) <= tag < F(1):
        raise ValueError("Expected a tag in [0,1) and a length from 0 to 64")
    split = F(weights[0], sum(weights))
    result = ""
    for _ in range(length):
        if tag < split:
            result += "A"
            tag /= split
        else:
            result += "B"
            tag = (tag - split) / (1 - split)
    return result


def phrase_rate_control():
    # A fixed Tunstall dictionary for the declared memoryless source.
    phrases = ("AAA", "AAB", "AB", "B")
    probabilities = [interval(phrase)[1] - interval(phrase)[0] for phrase in phrases]
    denominator = lcm(*(p.denominator for p in probabilities))
    counts = [int(p * denominator) for p in probabilities]
    bits_per_phrase = 2
    source_symbols = sum(count * len(phrase) for count, phrase in zip(counts, phrases))
    payload_bits = bits_per_phrase * sum(counts)
    expected_length = sum(p * len(phrase) for p, phrase in zip(probabilities, phrases))
    phrase_mean = sum(p * F(bits_per_phrase, len(phrase))
                      for p, phrase in zip(probabilities, phrases))
    return {
        "kind": "constructed phrase frequencies, not observed data or a finite-file codec",
        "rows": [{"phrase": phrase, "probability": str(p), "count": count}
                 for phrase, p, count in zip(phrases, probabilities, counts)],
        "phrase_count": sum(counts),
        "source_symbols": source_symbols,
        "payload_bits": payload_bits,
        "bits_per_phrase": bits_per_phrase,
        "expected_phrase_length": str(expected_length),
        "aggregate_bits_per_symbol": str(F(payload_bits, source_symbols)),
        "phrase_weighted_bits_per_symbol": str(phrase_mean),
        "excluded_costs": ["dictionary", "framing", "final partial phrase", "integrity metadata"],
    }


def results():
    rows = []
    expected_bits = F(0)
    for message in ("AA", "AB", "BA", "BB"):
        low, high = interval(message)
        prefix, start, end = shortest_prefix(low, high)
        expected_bits += (high - low) * len(prefix)
        rows.append({
            "message": message,
            "interval": "[" + str(low) + ", " + str(high) + ")",
            "dyadic_interval": "[" + str(start) + ", " + str(end) + ")",
            "prefix": prefix,
            "payload_bits": len(prefix),
            "fixed_width_bits": len(message),
            "packed_bytes": (len(prefix) + 7) // 8,
            "probability": str(high - low),
        })
    return {
        "kind": "synthetic exact-rational teaching example",
        "model": {"alphabet_order": ["A", "B"], "frequencies": list(MODEL)},
        "stopping_rule": "Exactly two symbols, supplied externally",
        "excluded_costs": ["model", "message length", "framing", "integrity metadata"],
        "rows": rows,
        "phrase_rate_control": phrase_rate_control(),
        "expected_payload_bits": str(expected_bits),
        "wrong_model": {"tag": "5/8", "length": 2, "frequencies": [1, 3],
                        "decoded": decode(F(5, 8), 2, (1, 3))},
        "limitations": "Not Opus, finite-precision range coding, a benchmark or paper replication.",
    }


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--write", action="store_true")
    args = parser.parse_args()
    destination = Path(__file__).with_name("results.json")
    encoded = json.dumps(results(), indent=2) + "\n"
    if args.write:
        destination.write_text(encoded)
    elif destination.read_text() != encoded:
        raise SystemExit("results.json differs from exact recomputation")
    else:
        print("Exact interval worksheet matches results.json")
