"""
SON OF ANTON — INTEGRATION PATCH FOR YOUR EXISTING MESSAGE ROUTE

This is NOT a standalone file. These are the functions and code blocks
you need to ADD to your existing message-sending route (the one that
handles POST /chats/{chat_id}/messages and streams SSE back).

--- STEP 1: Add these imports at the top of your messages route file ---
"""

# Add to your imports:
import os
from ..services.file_processor import build_content_blocks_for_attachments

UPLOAD_DIR = os.getenv("UPLOAD_DIR", "uploads")


"""
--- STEP 2: In your request body model/parsing, add attachment_ids ---

Your existing body probably looks like:
  { content, model, max_tokens, reasoning_budget, knowledge_base_id }

Add:
  attachment_ids: list[str] = []

So it becomes:
  { content, model, max_tokens, reasoning_budget, knowledge_base_id, attachment_ids }
"""


"""
--- STEP 3: Where you build the Claude messages array, replace the simple
    text content with a content block array when attachments exist ---

BEFORE (you probably have something like):
    user_message_content = body.content
    # or
    messages_for_claude.append({"role": "user", "content": body.content})

AFTER (replace with):
"""


async def build_user_content(db, body_content: str, attachment_ids: list, chat_id: str):
    """
    Build Claude content blocks for a user message.
    If there are attachments, returns a list of content blocks.
    If no attachments, returns the plain text string (backward compatible).
    """
    if not attachment_ids:
        return [{"text": body_content}]

    import uuid as uuid_mod

    # Fetch attachment records
    att_uuids = [uuid_mod.UUID(aid) for aid in attachment_ids]
    attachments = await db.fetch(
        """
        SELECT id, filename, original_filename, mime_type, file_size, media_type, storage_path
        FROM attachments
        WHERE id = ANY($1) AND chat_id = $2
        """,
        att_uuids,
        uuid_mod.UUID(chat_id),
    )
    attachments = [dict(a) for a in attachments]

    # Build content blocks: text first, then file blocks
    content_blocks = []

    # Add the text message
    if body_content.strip():
        content_blocks.append({"text": body_content})

    # Add file content blocks
    file_blocks = build_content_blocks_for_attachments(attachments, UPLOAD_DIR)
    content_blocks.extend(file_blocks)

    # If no text was provided, add a default prompt
    if not body_content.strip():
        content_blocks.insert(0, {"text": "Please describe and analyze the attached file(s)."})

    # Link attachments to the message (do after message is saved)
    return content_blocks


"""
--- STEP 4: In your Claude API call, use the content blocks ---

Instead of:
    {"role": "user", "content": "user text here"}

Use:
    {"role": "user", "content": content_blocks}

Where content_blocks comes from build_user_content() above.

--- STEP 5: After saving the user message to DB, link attachments ---
"""


async def link_attachments_to_message(db, attachment_ids: list, message_id):
    """Call this after inserting the user message into your messages table."""
    import uuid as uuid_mod
    if attachment_ids:
        await db.execute(
            "UPDATE attachments SET message_id = $1 WHERE id = ANY($2)",
            message_id,
            [uuid_mod.UUID(aid) for aid in attachment_ids],
        )


"""
--- STEP 6: Register the attachments router in your main app file ---

In your main.py or app.py, add:

    from .routes.attachments import router as attachments_router
    app.include_router(attachments_router, prefix="/api")

--- STEP 7: Also serve uploaded files statically (optional, for image previews) ---

    from fastapi.staticfiles import StaticFiles
    app.mount("/uploads", StaticFiles(directory="uploads"), name="uploads")

--- DONE. That's it for the backend. ---
"""