import sys, json, os, re
from ace2ryahee.dapu.agent import resolve, negotiate, choose_path

MEMORY_FILE = os.path.expanduser("~/.dapu_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

def run(filepath):
    memory = load_memory()
    source = open(filepath).read()
    agents = parse(source)
    print(f"[Dapu] 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("[Dapu] Memory saved.")

if __name__ == "__main__":
    run(sys.argv[1])
def main():
    # This is the entry point that setup.py is looking for
    # Add your logic here, for example:
    if len(sys.argv) > 1:
        file_path = sys.argv[1]
        print(f"Processing file: {file_path}")
        # Call your parse logic here:
        # data = parse(open(file_path).read())
        # print(data)
    else:
        print("Please provide a file path.")

if __name__ == "__main__":
    main()
