#!/usr/bin/env python3
# Minimal file agent: an LLM that can list, read, write and append files
# inside a sandbox folder called 'workspace'.

import json
import requests
from pathlib import Path

API_URL = "https://api.groq.com/openai/v1/chat/completions"
API_KEY = ''
MODEL   = "openai/gpt-oss-120b"

WORKSPACE = (Path(__file__).parent / "workspace").resolve()
WORKSPACE.mkdir(exist_ok=True)

# ---------------------------
# 1. Tools: ordinary Python functions that work inside the workspace
#    (errors are simply raised; the agent loop reports them to the LLM)
# ---------------------------
def safe_path(path: str) -> Path:
    """Turn a relative path into an absolute one, but never leave the workspace."""
    full = (WORKSPACE / path.lstrip("/")).resolve()
    if not full.is_relative_to(WORKSPACE):        # blocks tricks like '../../secret'
        raise PermissionError("Access denied")
    return full

def list_files(path: str = "") -> str:
    items = sorted(safe_path(path).rglob("*"))
    lines = [f"{'[DIR] ' if p.is_dir() else '[FILE]'} {p.relative_to(WORKSPACE)}" for p in items]
    return "\n".join(lines) or "(empty)"

def read_file(path: str) -> str:
    return safe_path(path).read_text(encoding="utf-8")

def write_file(path: str, content: str) -> str:
    file = safe_path(path)
    file.parent.mkdir(parents=True, exist_ok=True)
    file.write_text(content, encoding="utf-8")
    return f"Wrote file: {path}"

def append_file(path: str, content: str) -> str:
    file = safe_path(path)
    file.parent.mkdir(parents=True, exist_ok=True)
    with open(file, "a", encoding="utf-8") as f:
        f.write(content)
    return f"Appended to file: {path}"

# ---------------------------
# 2. Tool descriptions: this is what the LLM sees (a JSON schema per tool).
#    Each description is built step by step from small dictionaries.
# ---------------------------
# --- list_files ---
LF_properties = { "path": { "type"       : "string",
                            "description": "Optional subdirectory; empty means workspace root."}
                }
LF_parameters = { "type"      : "object",
                  "properties": LF_properties
                }
LF_function   = { "name"       : "list_files",
                  "description": "List all files and directories in the workspace.",
                  "parameters" : LF_parameters
                }
list_files_tool = { "type"    : "function",
                    "function": LF_function
                  }

# --- read_file ---
RF_properties = { "path": { "type"       : "string",
                            "description": "Path of the file."}
                }
RF_parameters = { "type"      : "object",
                  "properties": RF_properties,
                  "required"  : ["path"]
                }
RF_function   = { "name"       : "read_file",
                  "description": "Read the contents of a text file.",
                  "parameters" : RF_parameters
                }
read_file_tool = { "type"    : "function",
                   "function": RF_function
                 }

# --- write_file ---
WF_properties = { "path"   : { "type"       : "string",
                               "description": "Path of the file."},
                  "content": { "type"       : "string",
                               "description": "Content to write."}
                }
WF_parameters = { "type"      : "object",
                  "properties": WF_properties,
                  "required"  : ["path", "content"]
                }
WF_function   = { "name"       : "write_file",
                  "description": "Write content to a file (creates or overwrites it).",
                  "parameters" : WF_parameters
                }
write_file_tool = { "type"    : "function",
                    "function": WF_function
                  }

# --- append_file ---
AF_properties = { "path"   : { "type"       : "string",
                               "description": "Path of the file."},
                  "content": { "type"       : "string",
                               "description": "Content to append."}
                }
AF_parameters = { "type"      : "object",
                  "properties": AF_properties,
                  "required"  : ["path", "content"]
                }
AF_function   = { "name"       : "append_file",
                  "description": "Append content to a file (creates it if missing).",
                  "parameters" : AF_parameters
                }
append_file_tool = { "type"    : "function",
                     "function": AF_function
                   }

# list of all tool descriptions, sent to the LLM
TOOL_DEFS = [list_files_tool, read_file_tool, write_file_tool, append_file_tool]

# name (string sent by the LLM) -> Python function
TOOL_FUNCS = {f.__name__: f for f in (list_files, read_file, write_file, append_file)}

# ---------------------------
# 3. Talking to the LLM
# ---------------------------
def ask_llm(messages):
    payload = {"model": MODEL, "messages": messages, "tools": TOOL_DEFS}
    headers = {"Authorization": f"Bearer {API_KEY}"}
    resp = requests.post(API_URL, headers=headers, json=payload, timeout=60)
    resp.raise_for_status()
    return resp.json()["choices"][0]["message"]

# ---------------------------
# 4. The agent loop: repeat until the LLM stops asking for tools
# ---------------------------
def run_agent(messages):
    while True:
        reply = ask_llm(messages)
        messages.append(reply)

        tool_calls = reply.get("tool_calls")
        if not tool_calls:       # no tool wanted -> this is the final answer
            return reply["content"] or ""

        for call in tool_calls:
            name = call["function"]["name"]
            args = json.loads(call["function"]["arguments"])
            print(f"  [tool] {name}({args})")

            try:
                result = TOOL_FUNCS[name](**args)  # run the tool
            except Exception as e:                 # tell the LLM what went wrong
                result = f"ERROR: {e}"

            messages.append({"role": "tool",
                             "tool_call_id": call["id"],
                             "content": result})

# ---------------------------
# 5. Chat with the agent; the history is dumped to JSON when we quit
# ---------------------------
messages = [{"role": "system",
             "content": "You are a file assistant. Use the tools for ALL file operations, "
                        "never invent file contents, and read a file before modifying it. "
                        "All paths are relative to the workspace root."}]

print(f"File agent, workspace: {WORKSPACE}\nType 'exit' to quit.\n")

while True:
    try:
        user_input = input("> ").strip()
    except (EOFError, KeyboardInterrupt):
        break
    if user_input.lower() in ("exit", "quit"):
        break
    if not user_input:
        continue

    messages.append({"role": "user", "content": user_input})
    try:
        print("\n" + run_agent(messages) + "\n")
    except requests.exceptions.RequestException as e:
        print(f"\nAPI error: {e}\n")

with open("chat_history.json", "w", encoding="utf-8") as f:
    json.dump(messages, f, indent=2, ensure_ascii=False)
print("Bye!")
