"""Count and pack synthetic transcript events with a local chat tokenizer.

Run: python transcript_budget.py /path/to/Qwen3.5-9B
Requires Transformers with chat template support. Only local tokenizer files
are read. Counts use a fictional fixture and no model inference.
"""

import argparse
import json
from pathlib import Path

from transformers import AutoTokenizer


def fixture():
    topics = (
        "the difference between monthly subscriptions and one-off orders",
        "how pickup windows affected the people who worked evening shifts",
        "what the team learned after adding a delivery day in May",
    )
    for number in range(1, 306):
        topic = topics[number % len(topics)]
        yield (
            f"Event s{number:04d} at {(number - 1) * 22}s. The guest discusses {topic}. "
            "The host asks for an example. The guest gives one case from the pilot, "
            "then explains which condition limits how far that example applies. "
            "Use the original sentence IDs to check the scope of the answer."
        )


def pack(records, count_request, limit):
    if count_request([]) > limit:
        raise ValueError("The instructions alone exceed the input limit.")

    batch = []
    batches = []
    for record in records:
        candidate = [*batch, record]
        if count_request(candidate) <= limit:
            batch = candidate
            continue
        if not batch or count_request([record]) > limit:
            raise ValueError(f"One record exceeds the input limit: {record.split('.')[0]}")
        batches.append(batch)
        batch = [record]
    if batch:
        batches.append(batch)
    return batches


def count_with(tokenizer):
    def count(records):
        messages = [
            {"role": "system", "content": "Index the recording. Keep source IDs beside each finding."},
            {"role": "user", "content": "Group the following events by topic.\n\n" + "\n".join(records)},
        ]
        tokens = tokenizer.apply_chat_template(
            messages, tokenize=True, add_generation_prompt=True, return_dict=False
        )
        return len(tokens)

    return count


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("model_dir", type=Path)
    parser.add_argument("--window", type=int, default=16_384)
    parser.add_argument("--reserve", type=int, default=4096)
    parser.add_argument("--input-cap", type=int, default=12_000)
    args = parser.parse_args()
    if not 0 <= args.reserve < args.window or args.input_cap < 1:
        parser.error("Require a positive window and input cap, with a reserve smaller than the window.")

    tokenizer = AutoTokenizer.from_pretrained(args.model_dir, local_files_only=True)
    count_request = count_with(tokenizer)
    limit = min(args.input_cap, args.window - args.reserve)
    records = list(fixture())
    batches = pack(records, count_request, limit)
    print(json.dumps({
        "records": len(records),
        "limit": limit,
        "flatTokens": count_request(records),
        "batches": [
            {"records": len(batch), "tokens": count_request(batch)}
            for batch in batches
        ],
    }, indent=2))


if __name__ == "__main__":
    main()
