import os
import requests

BASE_URL = os.getenv("BASE_URL", "http://localhost:5000")
API_URL = f"{BASE_URL}/api/agent/system-prompt"
PROMPT_PATH = os.path.join(os.path.dirname(__file__), "agent", "system_prompt.txt")


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


print("Restoring system prompt from file...")
try:
    with open(PROMPT_PATH, "r", encoding="utf-8") as handle:
        original_prompt = handle.read()
except Exception as exc:
    print(f"ERROR: failed to read prompt file: {exc}")
    raise SystemExit(1)

try:
    response = requests.post(API_URL, json={"content": original_prompt})
    if response.status_code == 200:
        print("OK: prompt restored")
    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}")
