"""
Tool_OCR - File Access Control Service
Validates user permissions for file access
"""

import os
import logging
from typing import Optional
from sqlalchemy.orm import Session

from app.models.task import Task

logger = logging.getLogger(__name__)


class FileAccessService:
    """Service for validating file access permissions"""

    def validate_file_access(
        self,
        db: Session,
        user_id: int,
        task_id: str,
        file_path: Optional[str]
    ) -> tuple[bool, Optional[str]]:
        """
        Validate that user has access to the file

        Args:
            db: Database session
            user_id: User ID requesting access
            task_id: Task ID associated with the file
            file_path: Path to the file

        Returns:
            Tuple of (is_valid, error_message)
        """
        # Check if file path is provided
        if not file_path:
            return False, "File not available"

        # Get task and verify ownership
        task = db.query(Task).filter(
            Task.task_id == task_id,
            Task.user_id == user_id
        ).first()

        if not task:
            logger.warning(
                f"Unauthorized file access attempt: "
                f"user {user_id} tried to access task {task_id}"
            )
            return False, "Task not found or access denied"

        # Check if task is completed
        if task.status.value != "completed":
            return False, "Task not completed yet"

        # Check if file exists
        if not os.path.exists(file_path):
            logger.error(f"File not found: {file_path}")
            return False, "File not found on server"

        # Verify file is readable
        if not os.access(file_path, os.R_OK):
            logger.error(f"File not readable: {file_path}")
            return False, "File not accessible"

        logger.info(
            f"File access granted: user {user_id} accessing {file_path} "
            f"for task {task_id}"
        )
        return True, None


# Singleton instance
file_access_service = FileAccessService()
