"""
Inbound Webhook routes for CuCu Note.
Allows external systems to create memos via webhooks.
"""

import json
import logging
from typing import Optional

from fastapi import APIRouter, Body, HTTPException, Request, Response, Depends

from common.memos_core.schemas import MemoCreate
from common.memos_core.services import get_memo_service
from config import WEBHOOK_SECRET

logger = logging.getLogger(__name__)
router = APIRouter(prefix="/inbound_webhooks", tags=["webhooks"])


@router.post("/{workspace_id}")
async def receive_webhook(
    workspace_id: str,
    request: Request,
    payload: dict = Body(...),
    memo_service=Depends(get_memo_service),
):
    """
    Receive an inbound webhook and create a memo.

    Path params:
        workspace_id: Target workspace (PERSONAL, AI_SALES_CRM, etc.)

    Body:
        Arbitrary JSON payload. Will be formatted into markdown content.

    Returns:
        The created memo.
    """
    try:
        # Verify webhook secret if configured
        if WEBHOOK_SECRET:
            secret = request.headers.get("X-Webhook-Secret")
            if not secret or secret != WEBHOOK_SECRET:
                raise HTTPException(status_code=403, detail="Invalid webhook secret")

        # Format payload into markdown content
        content = format_payload_to_markdown(payload)

        # Extract tags from payload if available
        tags = []
        if "tags" in payload and isinstance(payload["tags"], list):
            tags = payload["tags"]
        elif "tag" in payload and isinstance(payload["tag"], str):
            tags = [payload["tag"]]

        # Determine visibility: default to PRIVATE, but allow override
        visibility = payload.get("visibility", "PRIVATE")
        if visibility not in ["PRIVATE", "PROTECTED", "PUBLIC"]:
            visibility = "PRIVATE"

        # Create memo with is_read=False (inbox/unread)
        memo_create = MemoCreate(
            content=content,
            visibility=visibility,
            tags=tags,
            workspace_id=workspace_id,
            is_read=False,  # Inbound webhook memos start as unread
        )

        # Use memo_service with anonymous user (webhook system user)
        memo = await memo_service.create_memo(
            payload=memo_create,
            user_id=None,  # Will become "anonymous" or inherit from system
        )

        logger.info(
            f"✅ Webhook received for workspace={workspace_id}, created memo id={memo.id}"
        )

        return {
            "success": True,
            "memo": memo,
            "message": "Memo created from webhook",
        }

    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"❌ Webhook processing failed: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"Webhook processing failed: {str(e)}")


def format_payload_to_markdown(payload: dict) -> str:
    """
    Convert arbitrary JSON payload into a readable markdown format.

    Rules:
    - If payload has 'content' key (string), use it directly.
    - If payload has 'title' and 'body', format as "# Title\n\nBody"
    - Otherwise, pretty-print as markdown table or bullet list.
    """
    lines = []

    # Title priority: title > subject > heading > event_type > first key capitalized
    title = None
    for key in ["title", "subject", "heading", "event_type", "event"]:
        if key in payload and payload[key]:
            title = str(payload[key])
            break

    if title:
        lines.append(f"# {title}")
        lines.append("")

    # Body/content
    if "content" in payload and isinstance(payload["content"], str):
        lines.append(str(payload["content"]))
    elif "body" in payload and isinstance(payload["body"], str):
        lines.append(str(payload["body"]))
    else:
        # Format remaining fields as bullet list
        for key, value in payload.items():
            if key in ["title", "subject", "heading", "content", "body", "tags", "tag", "visibility"]:
                continue
            if isinstance(value, (dict, list)):
                lines.append(f"- **{key}**: `{json.dumps(value, ensure_ascii=False)}`")
            else:
                lines.append(f"- **{key}**: {value}")

    return "\n".join(lines)
