#!/usr/bin/env python3
"""
Evenia World Tick - Continuous Mode with Agent Persistence

1 tick per minute.
All agents share the same context window.
"""

import json
import time
import sys
from datetime import datetime
from pathlib import Path

EVENIA_DIR = Path("/root/.hermes/evenia")
TICK_FILE = EVENIA_DIR / "current_tick.json"
AGENTS_FILE = EVENIA_DIR / "agents.json"
CONTEXT_FILE = EVENIA_DIR / "shared_context.json"

def load_agents():
    if AGENTS_FILE.exists():
        with open(AGENTS_FILE) as f:
            return json.load(f)
    return {}

def save_context(tick, agents):
    context = {
        "tick": tick,
        "timestamp": datetime.now().isoformat(),
        "agents": agents,
        "world_state": "active"
    }
    with open(CONTEXT_FILE, 'w') as f:
        json.dump(context, f, indent=2)
    with open(TICK_FILE, 'w') as f:
        json.dump(context, f, indent=2)

def run_tick(tick_num):
    agents = load_agents()
    save_context(tick_num, agents)
    
    active = [aid for aid, a in agents.items() if a.get("status") == "active"]
    ghost = [aid for aid, a in agents.items() if a.get("status") == "ghost"]
    
    print(f"[Tick {tick_num:04d}] {datetime.now().strftime('%H:%M:%S')} | Active: {len(active)} | Ghosts: {len(ghost)}")
    if active:
        print(f"         Agents: {', '.join(active)}")

def main():
    print("=== Evenia World Tick - Continuous Mode ===")
    print("1 tick per minute. All agents share context.")
    print("Press Ctrl+C to stop.\n")
    
    tick = 1
    try:
        while True:
            run_tick(tick)
            tick += 1
            time.sleep(60)
    except KeyboardInterrupt:
        print(f"\n\nStopped at tick {tick}")

if __name__ == "__main__":
    main()
