import json
from dapu.backend import query_local as query_llm

def resolve(name, goal, constraint, memory):
    system = "Reply only with JSON: {\"state\": \"value\", \"reason\": \"why\"}"
    user = f"Goal: {goal}. Constraint: {constraint}. Memory: {memory}. What is your state?"
    raw = query_llm(system, user)
    try:
        raw = raw.strip().replace("```json","").replace("```","").strip()
        return json.loads(raw)
    except:
        return {"state": raw, "reason": "ok"}

def choose_path(name, state, incentive):
    system = "Reply only with JSON: {\"choice\": \"chosen_path\", \"reason\": \"why\"}"
    user = f"Agent: {name}. Current state: {state}. Incentive rule: {incentive}. Which path do you choose?"
    raw = query_llm(system, user)
    try:
        raw = raw.strip().replace("```json","").replace("```","").strip()
        return json.loads(raw)
    except:
        return {"choice": raw, "reason": "ok"}

def negotiate(a, b):
    system = "Reply only with JSON: {\"agreed\": \"value\", \"reason\": \"why\"}"
    user = f"Agent A {a['name']} state: {a['state']}. Agent B {b['name']} state: {b['state']}. Find one agreed value."
    raw = query_llm(system, user)
    try:
        raw = raw.strip().replace("```json","").replace("```","").strip()
        return json.loads(raw)
    except:
        return {"agreed": raw, "reason": "ok"}
