"""Week 6: explicit character fixtures; optional actual tokenizer/template accounting."""
import argparse
import copy
import json
import tempfile
from pathlib import Path


def lesson1(tokenizer_dir=None):
    messages = [
        {'role': 'system', 'content': 'Never publish private data. Return a short answer.'},
        {'role': 'user', 'content': 'Current constraint: local output only.'},
        {'role': 'assistant', 'content': 'Old unrelated discussion. ' * 6},
        {'role': 'user', 'content': 'Summarize the current constraint.'}]
    kept = [messages[0], messages[1], messages[3]]
    char_count = sum(len(m['role']) + len(m['content']) for m in kept)
    assert char_count + 64 <= 300
    assert 'local output only' in kept[1]['content']
    print(json.dumps({'fixture_unit': 'characters, NOT model tokens', 'input_chars': char_count,
        'fixture_output_reserve_chars': 64, 'fixture_window_chars': 300}))
    if tokenizer_dir:
        from transformers import AutoTokenizer
        tokenizer = AutoTokenizer.from_pretrained(tokenizer_dir, local_files_only=True, trust_remote_code=False)
        token_ids = tokenizer.apply_chat_template(kept, tokenize=True, add_generation_prompt=True)
        reserve = 32; window = 512
        assert len(token_ids) + reserve <= window
        print(json.dumps({'actual_tokenizer_directory': str(Path(tokenizer_dir).resolve()),
            'serialized_input_tokens': len(token_ids), 'reserved_output_tokens': reserve,
            'declared_token_window': window, 'remaining_tokens': window - reserve - len(token_ids)}))
        print('Actual tokenizer/template count; no model inference or server-template equivalence claim.')
    else:
        print('Actual model-token budgeting NOT run. Supply --tokenizer-dir for the tokenizer path.')


def lesson2():
    documents = [
        {'id': 'old', 'effective': 1, 'text': 'All cases retained 30 days.', 'superseded': True},
        {'id': 'new', 'effective': 2, 'text': 'Cases retained 90 days. Project blue exception: 120 days.', 'superseded': False},
        {'id': 'noise', 'effective': 2, 'text': 'Office plants watered on Friday.', 'superseded': False}]
    selected = [d for d in documents if d['id'] == 'new']
    assert sum(len(d['text']) for d in selected) <= 100
    answer = {'project': 'blue', 'retention_days': 120, 'source': selected[0]['id']}
    assert answer['source'] == 'new' and answer['retention_days'] == 120
    # A deterministic selector, not a language-model attention experiment.
    def first_match(rows):
        return next((120 if '120 days' in row['text'] else 30)
                    for row in rows if 'retained' in row['text'])
    order_effect = [first_match(documents), first_match(list(reversed(documents)))]
    assert order_effect == [30, 120]
    def authoritative(rows):
        return max((row for row in rows if not row['superseded'] and 'retained' in row['text']),
                   key=lambda row: row['effective'])['id']
    assert authoritative(documents) == authoritative(list(reversed(documents))) == 'new'
    print(json.dumps({'fixture_budget_unit': 'characters', 'answer': answer,
        'irrelevant_characters_removed': len(documents[2]['text']),
        'first_match_fixture_order_results': order_effect,
        'authoritative_source_both_orders': 'new', 'model_order_effect': 'not measured'}))


def compact(state):
    return copy.deepcopy({key: state[key] for key in
        ['facts', 'decisions', 'tentative', 'revoked', 'open_questions', 'sources']})


def lesson3():
    state = {'facts': {'project': 'blue'}, 'decisions': {'output': 'local'},
        'tentative': {'format': 'table'}, 'revoked': ['send_by_email'],
        'open_questions': ['retention owner'], 'sources': ['conversation:turn4']}
    with tempfile.TemporaryDirectory(prefix='academy-w06-') as folder:
        path = Path(folder) / 'state.json'
        for _ in range(3):
            state = compact(state)
            path.write_text(json.dumps(state), encoding='utf-8')
            state = json.loads(path.read_text(encoding='utf-8'))
        assert state['decisions']['output'] == 'local'
        assert state['tentative']['format'] == 'table'
        assert 'send_by_email' in state['revoked']
        assert 'format' not in state['decisions']
        assert state['sources'] == ['conversation:turn4']
    print('PASS three structured compactions and disk reloads preserve decision, tentative option, revocation, source')
    print('Deterministic structured-state fixture; free-form model summarization quality not measured.')


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--lesson', choices=['1', '2', '3', 'all'], default='all')
    parser.add_argument('--tokenizer-dir', help='Local saved Hugging Face tokenizer with its chat template')
    args = parser.parse_args()
    for number, function in enumerate([lambda: lesson1(args.tokenizer_dir), lesson2, lesson3], 1):
        if args.lesson in ('all', str(number)):
            function()


if __name__ == '__main__':
    main()
