"""Postgres store for custom interviewer personas."""

from __future__ import annotations

from datetime import datetime, timezone
from uuid import uuid4

from app.database import SessionLocal
from app.models.persona import CustomPersonaRecord


def _utc_now() -> datetime:
    return datetime.now(timezone.utc)


def create_persona(
    *,
    company_id: str,
    name: str,
    description: str,
    tone: str,
    depth: str,
    recommended_for: list[str],
    evaluation_criteria: list[str],
    interview_style: str,
    language: str,
    system_prompt: str | None,
    style_summary: str | None,
    persona_id: str | None = None,
    meta: dict | None = None,
) -> CustomPersonaRecord:
    db = SessionLocal()
    try:
        now = _utc_now()
        row = CustomPersonaRecord(
            persona_id=persona_id or str(uuid4()),
            company_id=company_id.strip(),
            name=name,
            description=description or "",
            tone=tone or "",
            depth=depth or "",
            recommended_for=list(recommended_for or []),
            evaluation_criteria=list(evaluation_criteria or []),
            interview_style=interview_style or "",
            language=language or "en",
            system_prompt=system_prompt,
            style_summary=style_summary,
            meta=dict(meta or {}),
            created_at=now,
            updated_at=now,
        )
        db.add(row)
        db.commit()
        db.refresh(row)
        db.expunge(row)
        return row
    finally:
        db.close()


def list_all() -> list[CustomPersonaRecord]:
    """Return every saved custom persona (newest first)."""
    db = SessionLocal()
    try:
        rows = (
            db.query(CustomPersonaRecord)
            .order_by(CustomPersonaRecord.updated_at.desc())
            .all()
        )
        for row in rows:
            db.expunge(row)
        return rows
    finally:
        db.close()


def list_by_company(company_id: str | None = None) -> list[CustomPersonaRecord]:
    """List personas. Omit company_id to return all."""
    cid = (company_id or "").strip()
    if not cid:
        return list_all()
    db = SessionLocal()
    try:
        rows = (
            db.query(CustomPersonaRecord)
            .filter(CustomPersonaRecord.company_id == cid)
            .order_by(CustomPersonaRecord.updated_at.desc())
            .all()
        )
        for row in rows:
            db.expunge(row)
        return rows
    finally:
        db.close()


def get_by_id(persona_id: str) -> CustomPersonaRecord | None:
    pid = (persona_id or "").strip()
    if not pid:
        return None
    db = SessionLocal()
    try:
        row = (
            db.query(CustomPersonaRecord)
            .filter(CustomPersonaRecord.persona_id == pid)
            .first()
        )
        if row is not None:
            db.expunge(row)
        return row
    finally:
        db.close()
