# [DEF:manifest_repository:Module]
# @TIER: STANDARD
# @PURPOSE: Persist and query distribution manifests.
# @LAYER: Infra

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

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

    def save(self, manifest: DistributionManifest) -> DistributionManifest:
        """
        @PURPOSE: Persist a manifest.
        @POST: Manifest is committed and refreshed.
        """
        with belief_scope("ManifestRepository.save"):
            self.db.add(manifest)
            self.db.commit()
            self.db.refresh(manifest)
            return manifest

    def get_by_id(self, manifest_id: str) -> Optional[DistributionManifest]:
        """
        @PURPOSE: Retrieve a manifest by ID.
        """
        with belief_scope("ManifestRepository.get_by_id"):
            return self.db.query(DistributionManifest).filter(DistributionManifest.id == manifest_id).first()

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

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

# [/DEF:manifest_repository:Module]