"""
ABOS AI Worker – Digital Asset Compliance / Law-Change Check
================================================================
Best-effort AI-reasoned check for whether a digital asset's category/jurisdiction might have
seen a relevant regulation change recently. Backend-facing only — called by
DigitalAssetComplianceScheduler (Java), which resolves the tenant's stored OpenRouter key before
forwarding the request here.

IMPORTANT LIMITATION: this worker has no live web-search tool. The model reasons from its
training data only, so this is NOT real-time legal research — every response is caveated as
best-effort/non-authoritative, and the frontend must present it that way too (not as a compliance
guarantee).
"""

from __future__ import annotations

import logging

from fastapi import APIRouter, HTTPException, status

from app.llm_client import call_openrouter
from app.schemas import ComplianceCheckRequest, ComplianceCheckResponse

logger = logging.getLogger(__name__)

compliance_ai_router = APIRouter()

_PROMPT = (
    "You are assisting a business compliance team. Based on the asset details below, reason "
    "about whether this category of asset/license/registration, in the given jurisdiction, may "
    "have seen a relevant regulation or law change recently that the team should look into. You "
    "have NO live internet access — base this only on general knowledge, and be conservative: if "
    "you are not aware of anything specific, say so plainly rather than speculating.\n\n"
    "Respond as a JSON object with exactly these keys:\n"
    "{\n"
    "  \"summary\": \"2-4 sentence plain-language note for a non-lawyer, always including a "
    "caveat that this is a best-effort AI note, not legal advice, and the team should verify with "
    "an authoritative source\",\n"
    "  \"hasPossibleChanges\": true or false\n"
    "}"
)


@compliance_ai_router.post(
    "/compliance/check-law-changes",
    response_model=ComplianceCheckResponse,
    status_code=status.HTTP_200_OK,
    summary="Best-effort AI check for possible law/regulation changes relevant to a digital asset",
    tags=["Backend-Facing"],
)
async def check_law_changes(request: ComplianceCheckRequest) -> ComplianceCheckResponse:
    context_lines = [f"Asset name: {request.asset_name}"]
    if request.category:
        context_lines.append(f"Category: {request.category}")
    if request.jurisdiction:
        context_lines.append(f"Jurisdiction: {request.jurisdiction}")
    if request.compliance_notes:
        context_lines.append(f"Existing compliance notes: {request.compliance_notes}")
    if request.last_checked_at:
        context_lines.append(f"Last checked: {request.last_checked_at}")
    context_text = "\n".join(context_lines)

    try:
        data, model_used = await call_openrouter(
            openrouter_key=request.openrouter_key,
            prompt=_PROMPT,
            document_text=context_text,
            model=request.model,
        )
    except Exception as exc:
        logger.error("Compliance/law-change check failed: %s", exc)
        raise HTTPException(
            status_code=status.HTTP_502_BAD_GATEWAY,
            detail=f"Compliance check failed: {exc}",
        ) from exc

    summary = str(data.get("summary") or "No summary returned.")
    has_possible_changes = bool(data.get("hasPossibleChanges", False))
    return ComplianceCheckResponse(
        summary=summary, has_possible_changes=has_possible_changes, model_used=model_used
    )
