"""
ABOS AI Worker – Project/Workitem Description Enhancer Router
================================================================
Drafts or polishes the Description field on a Project or any level of its
work-item hierarchy (Feature/PBI/Task/Bug/Spike, Milestone/Activity/Deliverable,
Goal/ToDo/ActionItem) via OpenRouter. Backend-facing only — called by Spring
Boot's ProjectAiController, which resolves the tenant's stored OpenRouter key
before forwarding the request here (this service never persists a key).
"""

from __future__ import annotations

import logging

from fastapi import APIRouter, HTTPException, status

from app.llm_client import call_openrouter_text
from app.schemas import EnhanceTextRequest, EnhanceTextResponse

logger = logging.getLogger(__name__)

project_ai_router = APIRouter()

_SYSTEM_MESSAGE = (
    "You are a precise, concise business/technical writing assistant embedded in a project "
    "management tool. You write clear, professional descriptions for project and work-item "
    "records. Respond with ONLY the description text itself — no headings, no markdown, no "
    "preamble like 'Here is a description', no quotation marks around it."
)


def _build_user_message(request: EnhanceTextRequest) -> str:
    context_lines = [f"Record type: {request.item_type}", f"Title: {request.title}"]
    if request.parent_context:
        context_lines.append(f"Parent context: {request.parent_context}")

    if request.existing_description and request.existing_description.strip():
        context_lines.append(f"Current draft description:\n{request.existing_description.strip()}")
        instruction = (
            "Polish and expand the current draft description above — fix grammar, tighten "
            "wording, and add relevant detail implied by the title and context, but preserve "
            "its original intent. Keep it to 2-4 sentences."
        )
    else:
        instruction = (
            "Write a clear, professional description for this record from its title and "
            "context. Keep it to 2-4 sentences."
        )

    return "\n".join(context_lines) + "\n\n" + instruction


@project_ai_router.post(
    "/enhance-text",
    response_model=EnhanceTextResponse,
    status_code=status.HTTP_200_OK,
    summary="Draft or polish a Project/work-item description via OpenRouter",
    tags=["Backend-Facing"],
)
async def enhance_text(request: EnhanceTextRequest) -> EnhanceTextResponse:
    try:
        description, model_used = await call_openrouter_text(
            openrouter_key=request.openrouter_key,
            system_message=_SYSTEM_MESSAGE,
            user_message=_build_user_message(request),
            model=request.model,
        )
    except Exception as exc:
        logger.error("Description enhancement failed: %s", exc)
        raise HTTPException(
            status_code=status.HTTP_502_BAD_GATEWAY,
            detail=f"Description enhancement failed: {exc}",
        ) from exc

    return EnhanceTextResponse(description=description, model_used=model_used)
