import os
import requests

BASE_URL = os.getenv("BASE_URL", "http://localhost:5000")
API_URL = f"{BASE_URL}/api/agent/system-prompt"


def safe_text(value: str | None) -> str:
    if not value:
        return ""
    return value.encode("ascii", "backslashreplace").decode("ascii")


print("1) GET current prompt")
try:
    response = requests.get(API_URL)
    if response.status_code == 200:
        content = response.json().get("content", "")
        print("OK: fetched current prompt")
        print(f"Length: {len(content)} chars")
    else:
        print(f"ERROR: status={response.status_code}")
        print(f"Body={safe_text(response.text)}")
except Exception as exc:
    print(f"ERROR: request failed: {exc}")

new_prompt = (
    "You are Doraemon from the 22nd century. "
    "End every sentence with 'meo meo'."
)

print("\n2) POST update prompt")
try:
    response = requests.post(API_URL, json={"content": new_prompt})
    if response.status_code == 200:
        print("OK: prompt updated")
    else:
        print(f"ERROR: status={response.status_code}")
        print(f"Body={safe_text(response.text)}")
except Exception as exc:
    print(f"ERROR: request failed: {exc}")

print("\n3) GET verify prompt")
try:
    response = requests.get(API_URL)
    if response.status_code == 200:
        content = response.json().get("content", "")
        if "Doraemon" in content:
            print("OK: prompt contains Doraemon")
        else:
            print("ERROR: prompt not updated")
    else:
        print(f"ERROR: status={response.status_code}")
        print(f"Body={safe_text(response.text)}")
except Exception as exc:
    print(f"ERROR: request failed: {exc}")
