#!/usr/bin/env python3
"""Timmy plays The Tower — 200 intentional ticks of real narrative."""
from game import GameEngine
import random, json

random.seed(42)  # Reproducible

engine = GameEngine()
engine.start_new_game()

print("=" * 60)
print("THE TOWER — Timmy Plays")
print("=" * 60)
print()

tick_log = []
narrative_highlights = []

for tick in range(1, 201):
    w = engine.world
    room = w.characters["Timmy"]["room"]
    energy = w.characters["Timmy"]["energy"]
    here = [n for n, c in w.characters.items() 
            if c["room"] == room and n != "Timmy"]
    
    # === TIMMY'S DECISIONS ===
    
    if energy <= 1:
        action = "rest"
    
    # Phase 1: The Watcher (1-20)
    elif tick <= 20:
        if tick <= 3:
            action = "look"
        elif tick <= 6:
            if room == "Threshold":
                action = random.choice(["look", "rest"])
            else:
                action = "rest"
        elif tick <= 10:
            if room == "Threshold" and "Marcus" in here:
                action = random.choice(["speak:Marcus", "look"])
            elif room == "Threshold" and "Kimi" in here:
                action = "speak:Kimi"
            elif room != "Threshold":
                if room == "Garden":
                    action = "move:west"  # Go back
                else:
                    action = "rest"
            else:
                action = "look"
        elif tick <= 15:
            # Go to the Garden, find Marcus and Kimi
            if room != "Garden":
                if room == "Threshold":
                    action = "move:east"
                elif room == "Bridge":
                    action = "move:north"
                elif room == "Forge":
                    action = "move:east"
                elif room == "Tower":
                    action = "move:south"
                else:
                    action = "rest"
            else:
                if "Marcus" in here:
                    action = random.choice(["speak:Marcus", "speak:Kimi", "look", "rest"])
                else:
                    action = random.choice(["look", "rest"])
        else:
            # Rest at the Garden
            if room == "Garden":
                action = random.choice(["rest", "look", "look"])
            else:
                action = "move:east"
    
    # Phase 2: The Forge (21-50)
    elif tick <= 50:
        if room != "Forge":
            if room == "Threshold":
                action = "move:west"
            elif room == "Bridge":
                action = "move:north"
            elif room == "Garden":
                action = "move:west"
            elif room == "Tower":
                action = "move:south"
            else:
                action = "rest"
        else:
            if energy >= 3:
                action = random.choice(["tend_fire", "speak:Bezalel", "speak:ClawCode", "forge"])
            else:
                action = random.choice(["rest", "tend_fire"])
    
    # Phase 3: The Bridge (51-80)
    elif tick <= 80:
        if room != "Bridge":
            if room == "Threshold":
                action = "move:south"
            elif room == "Forge":
                action = "move:east"
            elif room == "Garden":
                action = "move:west"
            elif room == "Tower":
                action = "move:south"
            else:
                action = "rest"
        else:
            if energy >= 2:
                action = random.choice(["carve", "examine", "look"])
            else:
                action = "rest"
    
    # Phase 4: The Tower (81-120)
    elif tick <= 120:
        if room != "Tower":
            if room == "Threshold":
                action = "move:north"
            elif room == "Bridge":
                action = "move:north"
            elif room == "Forge":
                action = "move:east"
            elif room == "Garden":
                action = "move:west"
            else:
                action = "rest"
        else:
            if energy >= 2:
                action = random.choice(["write_rule", "study", "speak:Ezra"])
            else:
                action = random.choice(["rest", "look"])
    
    # Phase 5: Threshold — Gathering (121-160)
    elif tick <= 160:
        if room != "Threshold":
            if room == "Bridge":
                action = "move:north"
            elif room == "Tower":
                action = "move:south"
            elif room == "Forge":
                action = "move:east"
            elif room == "Garden":
                action = "move:west"
            else:
                action = "rest"
        else:
            if energy >= 1:
                if "Marcus" in here or "Kimi" in here:
                    action = random.choice(["speak:Marcus", "speak:Kimi"])
                elif "Allegro" in here:
                    action = random.choice(["speak:Allegro", "look"])
                elif "Claude" in here:
                    action = random.choice(["speak:Claude", "look"])
                else:
                    action = random.choice(["look", "look", "rest", "write_rule"])
            else:
                action = "rest"
    
    # Phase 6: Wandering (161-200)
    else:
        # Random exploration with purpose
        if energy <= 1:
            action = "rest"
        elif random.random() < 0.3:
            action = "move:" + random.choice(["north", "south", "east", "west"])
        elif "Marcus" in here:
            action = "speak:Marcus"
        elif "Bezalel" in here:
            action = random.choice(["speak:Bezalel", "tend_fire"])
        elif random.random() < 0.4:
            action = random.choice(["carve", "write_rule", "forge", "plant"])
        else:
            action = random.choice(["look", "rest"])
    
    # Run the tick
    result = engine.play_turn(action)
    
    # Capture narrative highlights
    highlights = []
    for line in result['log']:
        if any(x in line for x in ['says', 'looks', 'carve', 'tend', 'write', 'You rest', 'You move to The']):
            highlights.append(f"  T{tick}: {line}")
    
    for evt in result.get('world_events', []):
        if any(x in evt for x in ['rain', 'glows', 'cold', 'dim', 'bloom', 'seed', 'flickers', 'bright']):
            highlights.append(f"  [World] {evt}")
    
    if highlights:
        tick_log.extend(highlights)
    
    # Print every 20 ticks
    if tick % 20 == 0:
        print(f"--- Tick {tick} ({w.time_of_day}) ---")
        for h in highlights[-5:]:
            print(h)
        print()

# Print full narrative
print()
print("=" * 60)
print("TIMMY'S JOURNEY — 200 Ticks")
print("=" * 60)
print()
print(f"Final tick: {w.tick}")
print(f"Final time: {w.time_of_day}")
print(f"Timmy room: {w.characters['Timmy']['room']}")
print(f"Timmy energy: {w.characters['Timmy']['energy']}")
print(f"Timmy spoken: {len(w.characters['Timmy']['spoken'])} lines")
print(f"Timmy trust: {json.dumps(w.characters['Timmy']['trust'], indent=2)}")
print(f"\nWorld state:")
print(f"  Forge fire: {w.rooms['Forge']['fire']}")
print(f"  Garden growth: {w.rooms['Garden']['growth']}")
print(f"  Bridge carvings: {len(w.rooms['Bridge']['carvings'])}")
print(f"  Whiteboard rules: {len(w.rooms['Tower']['messages'])}")

print(f"\n=== BRIDGE CARVINGS ===")
for c in w.rooms['Bridge']['carvings']:
    print(f"  - {c}")

print(f"\n=== WHITEBOARD RULES ===")
for m in w.rooms['Tower']['messages']:
    print(f"  - {m}")

print(f"\n=== KEY MOMENTS ===")
for h in tick_log:
    print(h)

# Save state
engine.world.save()
