import sys, json, os, re
from agent import resolve, negotiate, choose_path

MEMORY_FILE = "memory.json"

def load_memory():
    if os.path.exists(MEMORY_FILE):
        return json.load(open(MEMORY_FILE))
    return {}

def save_memory(mem):
    json.dump(mem, open(MEMORY_FILE, "w"), indent=2)

def parse(source):
    agents = []
    for m in re.finditer(r'agent\s+(\w+)\s*\{([^}]*)\}', source):
        name = m.group(1)
        body = m.group(2)
        a = {"name": name, "goal": "", "constraint": "", "memory": "", "incentive": ""}
        for line in body.splitlines():
            if ":" in line:
                k, _, v = line.partition(":")
                k, v = k.strip(), v.strip()
                if k in a:
                    a[k] = v
        agents.append(a)
    return agents

memory = load_memory()
source = open(sys.argv[1]).read()
agents = parse(source)
print(f"Loaded {len(agents)} agents\n")

states = []
for a in agents:
    if a['name'] in memory:
        a['memory'] = f"last state was {memory[a['name']]['state']}"
        print(f"[{a['name']}] recalled: {a['memory']}")
    print(f"Resolving {a['name']}...")
    r = resolve(a['name'], a['goal'], a['constraint'], a['memory'])
    a['state'] = r['state']
    memory[a['name']] = r
    print(f"  state -> {r}")
    if a['incentive']:
        print(f"  choosing path...")
        p = choose_path(a['name'], a['state'], a['incentive'])
        a['choice'] = p['choice']
        memory[a['name']]['choice'] = p['choice']
        print(f"  path  -> {p}")
    print()
    states.append(a)

if len(states) >= 2:
    print("Negotiating...")
    result = negotiate(states[0], states[1])
    print(f"  Agreed: {result}")
    memory['_last_negotiation'] = result

save_memory(memory)
print("\nMemory saved.")
