from fastapi import APIRouter, Request
from starlette.responses import JSONResponse

from backend.config import IDENTITY_FILE, SOUL_FILE, USER_FILE
from backend.memory import _load_soul_text, _load_user_text


router = APIRouter()


def _write_user_identity_text(content: str):
    USER_FILE.write_text(content, encoding="utf-8")
    try:
        if IDENTITY_FILE.exists():
            IDENTITY_FILE.write_text(content, encoding="utf-8")
    except Exception:
        pass


@router.get("/api/identity")
def api_get_identity():
    return {"soul": _load_soul_text(), "user": _load_user_text()}


@router.put("/api/identity/soul")
async def api_put_soul(request: Request):
    try:
        body = await request.json()
        SOUL_FILE.write_text(body.get("content", ""), encoding="utf-8")
        return {"ok": True}
    except Exception as exc:
        return JSONResponse({"ok": False, "error": str(exc)}, status_code=500)


@router.put("/api/identity/user")
async def api_put_user(request: Request):
    try:
        body = await request.json()
        _write_user_identity_text(body.get("content", ""))
        return {"ok": True}
    except Exception as exc:
        return JSONResponse({"ok": False, "error": str(exc)}, status_code=500)


@router.delete("/api/identity/user")
def api_clear_user_profile():
    try:
        _write_user_identity_text("# User Profile\n")
        return {"ok": True}
    except Exception as exc:
        return JSONResponse({"ok": False, "error": str(exc)}, status_code=500)