"""Print every number the lesson quotes. Run: PYTHONDONTWRITEBYTECODE=1 python3 show_numbers.py"""
from prefix_cache import (AGES, DEFAULT_AGE, DEFAULT_DOC, DOC_LENGTHS, EARLIER, PRESETS, RULES, Cache, bill_request, break_even_reads,
                          chat_bill as lesson7, chat_cost, dollars, first_word_seconds, mark_tokens, merges, money, percent_less, tokens, view)


def main() -> None:
    chat, (p_in, p_out) = lesson7.EXAMPLE, lesson7.EXAMPLE_PRICES
    print("tokenizer merges:", len(merges()), "| earlier request:", len(tokens(EARLIER, 0)), "text tokens,", len(tokens(EARLIER, DEFAULT_DOC)), "with the document")
    print()
    print("widget, rule A, document", DEFAULT_DOC, "tokens, earlier request", DEFAULT_AGE, "minute ago; mark at", mark_tokens(EARLIER, DEFAULT_DOC), "tokens")
    for marked in (True, False):
        for preset in PRESETS:
            v = view(EARLIER, preset["text"], RULES[0], DEFAULT_DOC, DEFAULT_AGE, marked)
            print(f"  {'marked' if marked else 'unmarked'}, {preset['name']}: {v['match']} | {v['billed']} | {v['cost']} | {v['why']} | old {v['oldCount']} new {v['newCount']}")
    print()
    print("rule | write x | read x | minimum | lifetime | reads to pay back one write, (w - p) / (p - h)")
    for r in RULES:
        w, h = r.write / r.price, r.read / r.price
        print(f"  {r.key} {r.label}: price {r.price} write {r.write} read {r.read} out {r.output} | {w}x {h}x | {r.minimum} | {r.lifetime} min | {(r.write - r.price) / (r.price - r.read):.2f} -> {break_even_reads(r)}")
    print()
    base = lesson7.bill(chat, p_in, p_out)
    print(f"lesson 7 chat {chat}: input {base.input_tokens:,} tokens, ${base.input_cost}, output ${base.output_cost}, total ${base.total}")
    for r in RULES:
        for label, kwargs in (("every minute", dict(gap=1)), ("every 6 minutes", dict(gap=6)), ("every 40 minutes", dict(gap=40)),
                              ("clock line first, every minute", dict(gap=1, stamp=True))):
            on = chat_cost(chat, r, **kwargs)
            off = chat_cost(chat, r, cached=False, **kwargs)
            print(f"  {r.key} {label}: input {dollars(on['input'])} vs {dollars(off['input'])} | total {dollars(on['total'])} vs {dollars(off['total'])} "
                  f"({percent_less(off['total'], on['total'])}% less) | read {on['read']:,} written {on['written']:,} plain {on['plain']:,}")
    on = chat_cost(chat, RULES[0])
    print(f"  rule A hit rate: {on['read']:,} / {on['read'] + on['written'] + on['plain']:,} = {on['read'] / (on['read'] + on['written'] + on['plain']):.0%}; input sums {on['read']:,} x 0.10 + {on['written']:,} x 2.50 per million")
    print()
    for total, read in ((2900, 2640), (8020, 8000), (1280, 1200), (560, 0)):
        full, rest = first_word_seconds(total, read)
        print(f"  best-case reading, {total:,} tokens, {read:,} reused: {full * 1000:.1f} ms -> {rest * 1000:.1f} ms")
    print()
    print("break-even by minimum reads in a 1,200-token start, rule A: cost of n requests")
    for n in (1, 2, 3, 4, 5):
        c = Cache(RULES[0])
        total = sum(c.request([("doc", i) for i in range(1200)], k).units for k in range(n))
        print(f"  {n} requests: {money(total)} vs {money(n * 1200 * RULES[0].units('price'))} without")
    marked = bill_request(RULES[0], 1200, 0, mark=1000)
    print(f"mark=1000 of 1,200 on rule A: read {marked.read}, written {marked.written}, plain {marked.plain}")
    print("ages:", AGES, "doc lengths:", DOC_LENGTHS)


if __name__ == "__main__":
    main()
