"""agent-loop.py: model + tools + ek loop. howitworksio.com/agent-loop/

Chhota sa coding agent, wahi loop jo reel mein dikhaya:
model sochta hai -> tool maangta hai -> tool ka result wapas model ke paas -> phir se.

Setup:
  pip install anthropic
  export ANTHROPIC_API_KEY=...        # apni key, code mein mat likho
  python agent-loop.py "tests chalao aur jo fail ho use fix karo"

Har command chalane se pehle ye tumse poochta hai (y/n). Sirf apne project folder mein chalao.
"""
import os, subprocess, sys

MODEL = os.environ.get("MODEL", "claude-fable-5-1")  # koi bhi tool-use wala Claude model
MAX_LOOPS = 50          # safety: loop kitni baar chal sakta hai
MAX_MESSAGES = 40       # isse zyada messages = "memory bhar gayi" -> summary

TOOLS = [
    {"name": "read_file", "description": "Read a text file from the project.",
     "input_schema": {"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]}},
    {"name": "write_file", "description": "Overwrite a text file in the project with new content.",
     "input_schema": {"type": "object", "properties": {"path": {"type": "string"}, "content": {"type": "string"}},
                      "required": ["path", "content"]}},
    {"name": "run", "description": "Run a shell command (for example: npm test) and get its output.",
     "input_schema": {"type": "object", "properties": {"command": {"type": "string"}}, "required": ["command"]}},
]


def ask(q):
    return input(q).strip().lower() == "y"


def run_tool(name, args):
    try:
        if name == "read_file":
            return open(args["path"], encoding="utf-8").read()[:20000]
        if name == "write_file":
            if not ask(f"\nwrite {args['path']}? (y/n) "):
                return "user ne mana kiya"
            open(args["path"], "w", encoding="utf-8").write(args["content"])
            return "ok"
        if name == "run":
            if not ask(f"\nrun: {args['command']} ? (y/n) "):
                return "user ne mana kiya"
            p = subprocess.run(args["command"], shell=True, capture_output=True, text=True, timeout=300)
            return f"exit {p.returncode}\n{p.stdout[-8000:]}\n{p.stderr[-4000:]}"
        return f"unknown tool {name}"
    except Exception as e:  # error bhi result hai: model use padhkar agla step sochta hai
        return f"error: {e}"


def compact(client, task, messages):
    """Memory bhar gayi: purani baaton ki chhoti summary, aakhri kuch messages waise hi."""
    cut = len(messages) - 6
    while messages[cut]["role"] != "assistant":  # recent part assistant (tool_use) se shuru ho
        cut -= 1
    old, recent = messages[:cut], messages[cut:]
    text = "\n".join(str(m["content"])[:2000] for m in old)
    s = client.messages.create(model=MODEL, max_tokens=800, messages=[{"role": "user", "content":
        "Summarize this agent history in short bullets: what is done, what is left, important files.\n\n" + text}])
    summary = "".join(b.text for b in s.content if b.type == "text")
    return [{"role": "user", "content": f"{task}\n\nAb tak ka summary:\n{summary}"}] + recent


def agent(task, client):
    messages = [{"role": "user", "content": task}]
    for loop in range(1, MAX_LOOPS + 1):
        if len(messages) > MAX_MESSAGES:
            messages = compact(client, task, messages)
        reply = client.messages.create(model=MODEL, max_tokens=4000, tools=TOOLS, messages=messages)  # model sochta hai
        messages.append({"role": "assistant", "content": reply.content})
        for b in reply.content:
            if b.type == "text" and b.text.strip():
                print(f"\n[loop {loop}] {b.text}")
        calls = [b for b in reply.content if b.type == "tool_use"]
        if not calls:  # tool nahi maanga = kaam khatam
            return
        results = []
        for c in calls:  # tool chalao, result wapas model ko
            print(f"[loop {loop}] tool: {c.name} {c.input}")
            results.append({"type": "tool_result", "tool_use_id": c.id, "content": run_tool(c.name, c.input)})
        messages.append({"role": "user", "content": results})
    print(f"\n{MAX_LOOPS} loops ho gaye, ruk raha hoon.")


if __name__ == "__main__":
    if len(sys.argv) < 2:
        sys.exit('use: python agent-loop.py "apna task"')
    import anthropic
    agent(" ".join(sys.argv[1:]), anthropic.Anthropic())
