"""DB-backed CRUD for AI wizard conversation state.

Conversations have a 24-hour TTL. Every access validates ownership and expiry.
"""
import uuid
from datetime import datetime, timezone, timedelta
from typing import Any, Optional
from uuid import UUID

from fastapi import HTTPException, status
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from app.core.config import settings
from app.models.ai_conversation import AIConversation


async def create_conversation(
    user_id: UUID,
    account_id: UUID,
    wizard_state: dict[str, Any],
    db: AsyncSession,
) -> AIConversation:
    """Create a new AI wizard conversation."""
    conversation = AIConversation(
        user_id=user_id,
        account_id=account_id,
        status="foundation",
        wizard_state=wizard_state,
        messages=[],
        expires_at=datetime.now(timezone.utc)
        + timedelta(hours=settings.AI_CONVERSATION_TTL_HOURS),
    )
    db.add(conversation)
    await db.flush()
    return conversation


async def get_conversation(
    conversation_id: UUID,
    user_id: UUID,
    db: AsyncSession,
) -> AIConversation:
    """Get a conversation, validating ownership and expiry.

    Raises HTTPException 410 if expired, 404 if not found or wrong owner.
    """
    result = await db.execute(
        select(AIConversation).where(AIConversation.id == conversation_id)
    )
    conversation = result.scalar_one_or_none()

    if not conversation or conversation.user_id != user_id:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Conversation not found",
        )

    if conversation.expires_at < datetime.now(timezone.utc):
        conversation.status = "expired"
        await db.flush()
        raise HTTPException(
            status_code=status.HTTP_410_GONE,
            detail="Conversation expired. Please start a new AI build.",
        )

    return conversation


async def update_conversation(
    conversation_id: UUID,
    user_id: UUID,
    updates: dict[str, Any],
    db: AsyncSession,
) -> AIConversation:
    """Update a conversation's fields.

    Validates ownership and expiry before updating.
    """
    conversation = await get_conversation(conversation_id, user_id, db)

    for key, value in updates.items():
        if hasattr(conversation, key):
            setattr(conversation, key, value)

    await db.flush()
    return conversation
