# #region artifact_repository [C:3] [TYPE Module] [SEMANTICS clean-release, artifact, repository, persistence, crud]
# @BRIEF Persist and query candidate artifacts.
# @LAYER Infrastructure
# @RELATION DEPENDS_ON -> [EXT:Library:sqlalchemy]


from sqlalchemy.orm import Session

from src.core.logger import belief_scope
from src.models.clean_release import CandidateArtifact


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

    def save(self, artifact: CandidateArtifact) -> CandidateArtifact:
        """
        @PURPOSE: Persist an artifact.
        @POST: Artifact is committed and refreshed.
        """
        with belief_scope("ArtifactRepository.save"):
            self.db.add(artifact)
            self.db.commit()
            self.db.refresh(artifact)
            return artifact

    def save_all(self, artifacts: list[CandidateArtifact]) -> list[CandidateArtifact]:
        """
        @PURPOSE: Persist multiple artifacts in a single transaction.
        """
        with belief_scope("ArtifactRepository.save_all"):
            self.db.add_all(artifacts)
            self.db.commit()
            for artifact in artifacts:
                self.db.refresh(artifact)
            return artifacts

    def get_by_id(self, artifact_id: str) -> CandidateArtifact | None:
        """
        @PURPOSE: Retrieve an artifact by ID.
        """
        with belief_scope("ArtifactRepository.get_by_id"):
            return self.db.query(CandidateArtifact).filter(CandidateArtifact.id == artifact_id).first()

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

# #endregion artifact_repository
