#!/usr/bin/env python3
"""Generate an illustrative role ledger, not a general tournament rules engine.

Python 3.10+, standard library. Writes results.json and transitions.csv beside
this script (or --output DIR). Fixed three-seat rotation, one elimination.
No cards, random draws, chip transfers or strategy recommendations are modeled.
"""
import argparse
import csv
import io
import json
from pathlib import Path

SEATS = ('A', 'B', 'C')
FIELDS = ['case_id', 'previous_button', 'previous_small_blind',
          'previous_big_blind', 'eliminated', 'hand', 'button', 'small_blind',
          'big_blind', 'first_card', 'last_card', 'preflop_first', 'postflop_first']


def generate():
    cases, rows = [], []
    for button in range(3):
        previous = dict(zip(('button', 'small_blind', 'big_blind'),
                            (SEATS[(button + n) % 3] for n in range(3))))
        # Reconstruct who posted each of the last three big blinds, newest first.
        history = [SEATS[(button + 2 - age) % 3] for age in range(3)]
        for eliminated in SEATS:
            survivors = [seat for seat in SEATS if seat != eliminated]
            next_button = next(seat for seat in history if seat in survivors)
            case_id = f'button-{previous["button"]}-out-{eliminated}'
            hands = []
            for hand in range(1, 4):
                bb = next(seat for seat in survivors if seat != next_button)
                record = dict(hand=hand, button=next_button, small_blind=next_button,
                              big_blind=bb, first_card=bb, last_card=next_button,
                              preflop_first=next_button, postflop_first=bb)
                hands.append(record)
                rows.append(dict(case_id=case_id,
                                 **{'previous_' + k: v for k, v in previous.items()},
                                 eliminated=eliminated, **record))
                next_button = bb
            cases.append(dict(id=case_id, previous=previous,
                              eliminated=eliminated, hands=hands))
    return dict(schemaVersion=1,
                scope='Synthetic uninterrupted three-seat clockwise Holdem rotation; '
                      'one elimination; most recent surviving big blind gets the '
                      'first heads-up button; no seat moves or prior irregularities.',
                cases=cases), rows


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--output', type=Path, default=Path(__file__).resolve().parent)
    args = parser.parse_args()
    args.output.mkdir(parents=True, exist_ok=True)
    result, rows = generate()
    (args.output / 'results.json').write_text(json.dumps(result, indent=2) + '\n', encoding='utf-8', newline='\n')
    buffer = io.StringIO(newline='')
    writer = csv.DictWriter(buffer, fieldnames=FIELDS, lineterminator='\n')
    writer.writeheader()
    writer.writerows(rows)
    (args.output / 'transitions.csv').write_text(buffer.getvalue(), encoding='utf-8', newline='\n')
    print('Generated 9 labeled cases and 27 hand rows (3 distinct role cases).')


if __name__ == '__main__':
    main()
