from __future__ import annotations

import uuid
from typing import Optional, Tuple

from fastapi import UploadFile

from export.validator import ExportValidator
from export.scanner import IDExportScanner
from models.scan import ScanReport

# In-memory scan cache: session_id → (validated_data_dict, ScanReport)
# Replace with PocketBase/Redis when wiring auth
_scan_cache: dict = {}


class ScanService:
    def __init__(self, validator: ExportValidator, scanner: IDExportScanner):
        self.validator = validator
        self.scanner = scanner

    async def scan(self, file: UploadFile) -> ScanReport:
        """Validate and scan the uploaded idconvert_export.json."""
        content = await file.read()

        # Validate — raises FileValidationError on failure
        data = self.validator.validate(content)

        # Run lightweight scan for pre-conversion report
        report = self.scanner.scan(data)

        # Cache validated data dict and report by session ID
        session_id = str(uuid.uuid4())
        report.session_id = session_id
        _scan_cache[session_id] = (data, report)

        return report

    def get_cached(self, session_id: str) -> Optional[Tuple[dict, ScanReport]]:
        """Return (data_dict, report) for the session, or None if expired/missing."""
        return _scan_cache.get(session_id)
