"""Postgres store for versioned candidate resume profiles."""

from __future__ import annotations

from datetime import datetime, timezone
from typing import Any
from uuid import uuid4

from app.database import SessionLocal
from app.models.resume_profile import CandidateResumeProfileRecord


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


def _new_id() -> str:
    return f"rprof-{uuid4().hex[:16]}"


def get_latest(candidate_id: str) -> CandidateResumeProfileRecord | None:
    cid = (candidate_id or "").strip()
    if not cid:
        return None
    db = SessionLocal()
    try:
        row = (
            db.query(CandidateResumeProfileRecord)
            .filter(CandidateResumeProfileRecord.candidate_id == cid)
            .order_by(CandidateResumeProfileRecord.resume_version.desc())
            .first()
        )
        if row is not None:
            db.expunge(row)
        return row
    finally:
        db.close()


def get_by_candidate_hash(
    candidate_id: str, content_hash: str
) -> CandidateResumeProfileRecord | None:
    cid = (candidate_id or "").strip()
    ch = (content_hash or "").strip()
    if not cid or not ch:
        return None
    db = SessionLocal()
    try:
        row = (
            db.query(CandidateResumeProfileRecord)
            .filter(
                CandidateResumeProfileRecord.candidate_id == cid,
                CandidateResumeProfileRecord.content_hash == ch,
            )
            .first()
        )
        if row is not None:
            db.expunge(row)
        return row
    finally:
        db.close()


def next_version(candidate_id: str) -> int:
    latest = get_latest(candidate_id)
    if latest is None:
        return 1
    return int(latest.resume_version or 0) + 1


def save_profile(
    *,
    candidate_id: str,
    content_hash: str,
    raw_text: str | None,
    structured: dict[str, Any],
    blocks: list[Any] | None = None,
    company_id: str | None = None,
    source_url: str | None = None,
    filename: str | None = None,
    document_type: str | None = None,
    meta: dict[str, Any] | None = None,
) -> CandidateResumeProfileRecord:
    """Insert a new version, or return existing row for same candidate+hash."""
    existing = get_by_candidate_hash(candidate_id, content_hash)
    if existing is not None:
        return existing

    db = SessionLocal()
    try:
        now = _utc_now()
        version = 1
        latest = (
            db.query(CandidateResumeProfileRecord)
            .filter(CandidateResumeProfileRecord.candidate_id == candidate_id.strip())
            .order_by(CandidateResumeProfileRecord.resume_version.desc())
            .first()
        )
        if latest is not None:
            version = int(latest.resume_version or 0) + 1

        row = CandidateResumeProfileRecord(
            profile_id=_new_id(),
            candidate_id=candidate_id.strip(),
            company_id=(company_id or "").strip() or None,
            resume_version=version,
            content_hash=content_hash.strip(),
            source_url=source_url,
            filename=filename,
            document_type=document_type,
            raw_text=raw_text,
            structured=dict(structured or {}),
            blocks=list(blocks or []),
            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()
