from fastapi import APIRouter, HTTPException, Request

from app.services.repository import repo


router = APIRouter(prefix="/api/profile", tags=["profile"])


@router.get("")
async def get_profile():
    return {"profile": repo.get_profile(), "backend": repo.backend}


@router.post("/blacklist")
async def update_blacklist(request: Request):
    payload = await request.json()
    name = str(payload.get("name") or "").strip().lower()
    enabled = bool(payload.get("enabled", True))
    if not name:
        raise HTTPException(status_code=400, detail="Ingredient or term is required.")
    profile = repo.get_profile()
    items = list(profile.get("soft_blacklist") or [])
    existing = next((item for item in items if str(item.get("name") or "").strip().lower() == name), None)
    if existing:
        existing["enabled"] = enabled
    else:
        items.append({"name": name, "enabled": enabled})
    profile["soft_blacklist"] = sorted(items, key=lambda item: str(item.get("name") or ""))
    repo.save_profile(profile)
    return {"status": "ok", "profile": profile}


@router.post("/settings")
async def update_settings(request: Request):
    payload = await request.json()
    profile = repo.get_profile()
    if "notes" in payload:
        profile["notes"] = str(payload.get("notes") or "")
    if "auto_import_threshold" in payload:
        profile["auto_import_threshold"] = max(50, min(100, int(payload["auto_import_threshold"])))
    if "auto_import_enabled" in payload:
        profile["auto_import_enabled"] = bool(payload["auto_import_enabled"])
    repo.save_profile(profile)
    return {"status": "ok", "profile": profile}

