"""
The Tower World — Tick Handler
Every tick: world advances, wizards move, state commits.
"""
import subprocess
import os
from evennia.utils import search, logger

class WorldTick:
    def __init__(self):
        self.tick_count = self._load_tick_count()
        
    def _load_tick_count(self):
        try:
            with open('/tmp/tower-world-tick.txt') as f:
                return int(f.read().strip())
        except:
            return 0
    
    def _save_tick_count(self):
        with open('/tmp/tower-world-tick.txt', 'w') as f:
            f.write(str(self.tick_count))
    
    def advance(self):
        """Advance the world one tick."""
        self.tick_count += 1
        self._save_tick_count()
        
        # Get wizards
        wizards = search.search_object(typeclass='typeclasses.characters.Wizard')
        
        results = []
        for wizard in wizards:
            # Each wizard makes their autonomous move
            move = wizard.at_tick()
            if move:
                results.append(f"{wizard.key}: {move}")
        
        # Commit to git
        self._commit_tick(self.tick_count, results)
        
        return {
            'tick': self.tick_count,
            'moves': results,
        }
    
    def _commit_tick(self, tick, moves):
        world_dir = os.path.expanduser('~/.timmy/the-tower-world')
        move_text = ', '.join(moves) if moves else 'The world breathes.'
        
        try:
            subprocess.run(
                ['git', '-C', world_dir, 'add', '-A'],
                capture_output=True, timeout=10
            )
            subprocess.run(
                ['git', '-C', world_dir, 'commit', '-m', 
                 f'Tick #{tick} — {move_text}'],
                capture_output=True, timeout=10
            )
        except Exception as e:
            logger.log_msg(f"Tick commit failed: {e}")

# Global instance
TICK = WorldTick()

def tick_world():
    """Called by cron or Evennia ticker."""
    result = TICK.advance()
    return result
