# [DEF:publication_repository:Module]
# @TIER: STANDARD
# @PURPOSE: Persist and query publication records.
# @LAYER: Infra

from typing import Optional, List
from sqlalchemy.orm import Session
from src.models.clean_release import PublicationRecord
from src.core.logger import belief_scope

class PublicationRepository:
    """
    @PURPOSE: Encapsulates database operations for PublicationRecord.
    """
    def __init__(self, db: Session):
        self.db = db

    def save(self, record: PublicationRecord) -> PublicationRecord:
        """
        @PURPOSE: Persist a publication record.
        @POST: Record is committed and refreshed.
        """
        with belief_scope("PublicationRepository.save"):
            self.db.add(record)
            self.db.commit()
            self.db.refresh(record)
            return record

    def get_by_id(self, record_id: str) -> Optional[PublicationRecord]:
        """
        @PURPOSE: Retrieve a record by ID.
        """
        with belief_scope("PublicationRepository.get_by_id"):
            return self.db.query(PublicationRecord).filter(PublicationRecord.id == record_id).first()

    def get_latest_for_candidate(self, candidate_id: str) -> Optional[PublicationRecord]:
        """
        @PURPOSE: Retrieve the latest record for a candidate.
        """
        with belief_scope("PublicationRepository.get_latest_for_candidate"):
            return self.db.query(PublicationRecord)\
                .filter(PublicationRecord.candidate_id == candidate_id)\
                .order_by(PublicationRecord.published_at.desc())\
                .first()

    def list_by_candidate(self, candidate_id: str) -> List[PublicationRecord]:
        """
        @PURPOSE: List all records for a specific candidate.
        """
        with belief_scope("PublicationRepository.list_by_candidate"):
            return self.db.query(PublicationRecord).filter(PublicationRecord.candidate_id == candidate_id).all()

# [/DEF:publication_repository:Module]