"""File system asset repository."""

import shutil
from pathlib import Path

from noteflow.domain.ports.repositories import AssetRepository
from noteflow.domain.value_objects import MeetingId
from noteflow.infrastructure.logging import get_logger

logger = get_logger(__name__)


class FileSystemAssetRepository(AssetRepository):
    """File system implementation of AssetRepository."""

    def __init__(self, base_dir: Path) -> None:
        """Initialize repository with base directory.

        Args:
            base_dir: Root directory for meeting assets.
        """
        self.base_dir = base_dir

    async def delete_meeting_assets(
        self,
        meeting_id: MeetingId,
        asset_path: str | None = None,
    ) -> None:
        """Delete all assets associated with a meeting.

        Args:
            meeting_id: Meeting identifier.
            asset_path: Relative path for assets (defaults to str(meeting_id)).
        """
        # Use asset_path if provided, otherwise default to meeting_id
        storage_path = asset_path or str(meeting_id)
        meeting_dir = self.base_dir / storage_path

        # Security: ensure path stays under base_dir to prevent traversal
        resolved = meeting_dir.resolve()
        if not str(resolved).startswith(str(self.base_dir.resolve())):
            logger.warning(
                "Rejected path traversal attempt: %s (resolved to %s)",
                storage_path,
                resolved,
            )
            return

        if meeting_dir.exists():
            shutil.rmtree(meeting_dir)
            logger.info("Deleted meeting assets at %s", meeting_dir)
