"""Persist AI job drafts / publishes (gateway-owned ai_jobs table)."""

from __future__ import annotations

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

from app.database import SessionLocal
from app.models.jobs import AiJobRecord

logger = logging.getLogger(__name__)


def new_job_id() -> str:
    return f"job-{uuid4().hex[:12]}"


def save_job(
    *,
    job_id: str | None = None,
    status: str,
    role_title: str,
    title: str | None = None,
    markdown: str | None = None,
    sections: dict[str, Any] | None = None,
    validation: dict[str, Any] | None = None,
    company_id: str | None = None,
    created_by: str | None = None,
    platform_job_id: str | None = None,
    employment_type: str | None = None,
    location: str | None = None,
    years_of_experience: str | None = None,
    seniority: str | None = None,
    department: str | None = None,
    meta: dict[str, Any] | None = None,
) -> AiJobRecord:
    db = SessionLocal()
    try:
        jid = job_id or new_job_id()
        row = db.get(AiJobRecord, jid) if job_id else None
        now = datetime.now(timezone.utc)
        if row is None:
            row = AiJobRecord(job_id=jid, created_at=now)
            db.add(row)
        row.status = status
        row.role_title = role_title
        row.title = title
        row.markdown = markdown
        row.sections = sections or {}
        row.validation = validation
        row.company_id = company_id
        row.created_by = created_by
        row.platform_job_id = platform_job_id or row.platform_job_id
        row.employment_type = employment_type
        row.location = location
        row.years_of_experience = years_of_experience
        row.seniority = seniority
        row.department = department
        row.meta = meta or row.meta or {}
        row.updated_at = now
        db.commit()
        db.refresh(row)
        # Detach for use after session close
        db.expunge(row)
        return row
    except Exception:
        db.rollback()
        raise
    finally:
        db.close()


def get_job(job_id: str) -> AiJobRecord | None:
    db = SessionLocal()
    try:
        row = db.get(AiJobRecord, job_id)
        if row is not None:
            db.expunge(row)
        return row
    except Exception as exc:  # noqa: BLE001
        logger.warning("get_job failed %s: %s", job_id, exc)
        return None
    finally:
        db.close()
