from datetime import datetime

from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from app.models.generation_record import GenerationRecord
from app.utils.security import encrypt_temp_token, decrypt_temp_token


async def generate_temp_url(db: AsyncSession, record: GenerationRecord) -> str:
    """Generate a temporary encrypted URL for video access (1 hour expiry)."""
    if getattr(record, "deleted_at", None) is not None:
        return ""
    token = encrypt_temp_token(record.id, expires_in=3600)
    record.video_url_expires_at = datetime.now().replace(second=0, microsecond=0)
    # We store just the token, the full URL is constructed by the frontend
    return f"/api/generation-records/{record.id}/video?token={token}"


async def validate_and_get_record_id(token: str) -> str | None:
    """Validate a temp URL token and return the record_id if valid."""
    return decrypt_temp_token(token)


async def get_video_stream_url(db: AsyncSession, record_id: str) -> str | None:
    """Get the actual video URL for a record (for proxying/redirecting)."""
    result = await db.execute(
        select(GenerationRecord.video_url).where(
            GenerationRecord.id == record_id,
            GenerationRecord.deleted_at.is_(None),
        )
        .limit(1)
    )
    return result.scalar_one_or_none()
