"""远星邮航模型应用实验。仅使用 Python 标准库，输入为本地构造的模型回执和人工标签。"""
import argparse
import json
from fractions import Fraction


# m1：网关已经将不同供应商的终止原因映射成 complete / refused / truncated。
RECEIPTS = [
    ("A", "complete", '{"ship":"星桥","seats":4}'),
    ("B", "complete", '{"ship":"星桥","seats":7}'),
    ("C", "complete", '{"ship":"星桥","seats":true}'),
    ("D", "refused", ""),
    ("E", "truncated", '{"ship":"星桥","seats":'),
]


def read_receipt(reason, payload, available):
    if reason != "complete":
        return reason
    try:
        item = json.loads(payload)
    except json.JSONDecodeError:
        return "bad_json"
    if not isinstance(item, dict) or set(item) != {"ship", "seats"}:
        return "bad_shape"
    if not isinstance(item["ship"], str) or type(item["seats"]) is not int:
        return "bad_shape"
    if item["ship"] != "星桥" or not 1 <= item["seats"] <= available:
        return "outside_manifest"
    return "accepted"


def receipt_lab(available):
    states = {key: read_receipt(reason, payload, available) for key, reason, payload in RECEIPTS}
    assert states["C"] == "bad_shape"
    assert states["D"] == "refused" and states["E"] == "truncated"
    assert read_receipt("complete", "{}", available) == "bad_shape"
    assert read_receipt("complete", "{", available) == "bad_json"
    assert (states["B"] == "accepted") == (available >= 7)
    print(" ".join(f"{key}={value}" for key, value in states.items()))
    print("accepted=" + str(sum(value == "accepted" for value in states.values())))


# m2：模拟一个输入与输出共享窗口的模型。下列长度是实验给定的 token 数。
# 真实调用应使用对应模型计数，整包复算时还需计入角色、模板、工具定义等开销。
BLOCKS = [("history", 360), ("rule", 310), ("exception", 230), ("glossary", 60)]
REQUIRED = {"rule", "exception"}


def greedy_pack(blocks, budget):
    chosen = []
    for key, tokens in blocks:
        if tokens <= budget:
            chosen.append(key)
            budget -= tokens
    return chosen


def budget_lab(window):
    fixed_input, output_reserve, margin = 240, 260, 100
    budget = window - fixed_input - output_reserve - margin
    print(f"evidence_budget={budget}")
    if budget < 0:
        print("decision=reject_request")
        return
    naive = greedy_pack(BLOCKS, budget)
    print(f"arrival_order={','.join(naive) or '-'} complete={int(REQUIRED.issubset(naive))}")
    evidence = sorted(BLOCKS, key=lambda block: block[0] not in REQUIRED)
    chosen = greedy_pack(evidence, budget)
    if not REQUIRED.issubset(chosen):
        assert budget < sum(size for key, size in BLOCKS if key in REQUIRED)
        print("decision=need_more_room")
        return
    used = sum(size for key, size in BLOCKS if key in chosen)
    assert used <= budget
    print(f"evidence_first={','.join(chosen)} used={used} decision=answer")


# m3：单进程内模拟应用中继自己的追加日志。seq 由本中继分配并持久化在日志，
# 浏览器重连时读取同一日志；这里不假定模型 API 会自动重送相同事件。
FLIGHT = "letter-41"
LOG = [(1, "delta", "邮船"), (2, "delta", "已到"), (3, "end", "complete")]


def replay(events, committed):
    pieces = []
    last_seq = 0
    for seq, kind, content in events:
        if seq <= last_seq:
            continue
        if seq != last_seq + 1:
            return "gap", "".join(pieces)
        last_seq = seq
        if kind == "delta":
            pieces.append(content)
        elif kind == "end":
            if content != "complete":
                return content, "".join(pieces)
            text = "".join(pieces)
            committed.setdefault(FLIGHT, text)
            return "complete", text
    return "interrupted", "".join(pieces)


def streaming_lab(drop):
    committed = {}
    status, preview = replay(LOG[:1], committed)
    assert status == "interrupted" and not committed
    print(f"first={status} preview={preview} commits={len(committed)}")
    redelivery = [event for event in [LOG[0], *LOG] if event[0] != drop]
    status, text = replay(redelivery, committed)
    replay(redelivery, committed)
    print(f"replay={status} text={text or '-'} commits={len(committed)}")
    assert len(committed) == (0 if drop else 1)
    if not drop:
        assert committed[FLIGHT] == "邮船已到"
    assert replay([(1, "end", "truncated")], {})[0] == "truncated"


# m4：每封信给定业务线索、人工标注答案和两种模型的离线输出。1/4 为虚构计费单位。
MAIL = [
    # 分组、金标、轻型模型、复核模型
    ("single", "东港", "东港", "东港"),
    ("single", "杜衡", "杜衡", "杜衡"),
    ("single", "清晨", "清晨", "清晨"),
    ("single", "八号", "八号", "八号"),
    ("multi", "周三", "周二", "周三"),
    ("multi", "南栈", "北栈", "南栈"),
    ("multi", "一小时", "一小时", "半小时"),
    ("missing", "西塔", "东塔", "北塔"),
]


def routing_lab(floor):
    cheap_hits = sum(cheap == gold for _, gold, cheap, _ in MAIL)
    print(f"all_light correct={cheap_hits}/{len(MAIL)} cost={len(MAIL)}")
    answered = correct = cost = 0
    for kind, gold, cheap, strong in MAIL:
        if kind == "missing":
            continue
        output, units = (cheap, 1) if kind == "single" else (strong, 4)
        answered += 1
        cost += units
        correct += output == gold
    accuracy = Fraction(correct, answered) if answered else Fraction(0)
    coverage = Fraction(answered, len(MAIL))
    decision = "pass_fixture" if accuracy >= floor and coverage >= Fraction(3, 4) else "hold"
    assert 0 <= correct <= answered <= len(MAIL)
    print(f"routed correct={correct}/{answered} coverage={answered}/{len(MAIL)} cost={cost}")
    print(f"quality_floor={floor} coverage_floor=3/4 gate={decision}")


def bounded_integer(low, high):
    def parse(text):
        value = int(text)
        if not low <= value <= high:
            raise argparse.ArgumentTypeError(f"请输入 {low} 至 {high} 的整数")
        return value
    return parse


def quality_floor(text):
    try:
        value = Fraction(text)
    except (ValueError, ZeroDivisionError) as error:
        raise argparse.ArgumentTypeError("请输入 0 至 1 的分数或小数") from error
    if not 0 <= value <= 1:
        raise argparse.ArgumentTypeError("请输入 0 至 1 的分数或小数")
    return value


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    labs = parser.add_subparsers(dest="lab", required=True)
    labs.add_parser("m1").add_argument("--available-seats", type=bounded_integer(0, 100), default=6)
    labs.add_parser("m2").add_argument("--window", type=bounded_integer(1, 100000), default=1200)
    labs.add_parser("m3").add_argument("--drop-seq", type=bounded_integer(1, 3), default=None)
    labs.add_parser("m4").add_argument("--quality-floor", type=quality_floor, default=Fraction(9, 10))
    args = parser.parse_args()
    if args.lab == "m1":
        receipt_lab(args.available_seats)
    elif args.lab == "m2":
        budget_lab(args.window)
    elif args.lab == "m3":
        streaming_lab(args.drop_seq)
    else:
        routing_lab(args.quality_floor)
