# /opt/docker/dev/service_finder/backend/app/services/media_service.py
from PIL import Image
from PIL.ExifTags import TAGS, GPSTAGS
import logging
from typing import Tuple, Optional

logger = logging.getLogger(__name__)

class MediaService:
    @staticmethod
    def _convert_to_degrees(value) -> float:
        """ EXIF racionális koordináták konvertálása tizedes fokká. """
        try:
            d = float(value[0])
            m = float(value[1])
            s = float(value[2])
            return d + (m / 60.0) + (s / 3600.0)
        except (IndexError, ZeroDivisionError, TypeError):
            return 0.0

    @classmethod
    def extract_gps_info(cls, file_path: str) -> Optional[Tuple[float, float]]:
        """ GPS koordináták kinyerése a kép metaadataiból (Robot Hunt alapja). """
        try:
            with Image.open(file_path) as image:
                exif = image._getexif()
                if not exif: return None

                gps_info = {}
                for tag, value in exif.items():
                    if TAGS.get(tag) == "GPSInfo":
                        for t in value:
                            gps_info[GPSTAGS.get(t, t)] = value[t]

                if 'GPSLatitude' in gps_info and 'GPSLongitude' in gps_info:
                    lat = cls._convert_to_degrees(gps_info['GPSLatitude'])
                    if gps_info.get('GPSLatitudeRef') != "N": lat = -lat
                    
                    lon = cls._convert_to_degrees(gps_info['GPSLongitude'])
                    if gps_info.get('GPSLongitudeRef') != "E": lon = -lon

                    return lat, lon
        except Exception as e:
            logger.warning(f"EXIF kiolvasási hiba ({file_path}): {e}")
        return None