# /opt/docker/dev/service_finder/backend/app/workers/service/service_robot_4_validator_google.py
import asyncio
import httpx
import logging
import os
import sys
import json
from datetime import datetime
from sqlalchemy import text, update, func
from app.database import AsyncSessionLocal
from app.models.marketplace.service import ServiceProfile, ServiceStatus

logging.basicConfig(level=logging.INFO, format='%(asctime)s [%(levelname)s] Robot-4-Validator: %(message)s', stream=sys.stdout)
logger = logging.getLogger("Service-Robot-4-Google-Validator")

class QuotaManager:
    """ Szigorú napi limit figyelő a Google API-hoz, hogy soha többé ne legyen 250$-os számla! """
    def __init__(self, service_name: str, daily_limit: int):
        self.service_name = service_name
        self.daily_limit = daily_limit
        self.state_file = f"/app/temp/.quota_{service_name}.json"
        self._ensure_file()

    def _ensure_file(self):
        os.makedirs(os.path.dirname(self.state_file), exist_ok=True)
        if not os.path.exists(self.state_file):
            with open(self.state_file, 'w') as f:
                json.dump({"date": datetime.now().strftime("%Y-%m-%d"), "count": 0}, f)

    def can_make_request(self) -> bool:
        with open(self.state_file, 'r') as f:
            data = json.load(f)
        
        today = datetime.now().strftime("%Y-%m-%d")
        if data["date"] != today:
            data = {"date": today, "count": 0} 
            
        if data["count"] >= self.daily_limit:
            return False
            
        data["count"] += 1
        with open(self.state_file, 'w') as f:
            json.dump(data, f)
        return True

class GoogleValidator:
    """
    Service Robot 4: Mesterlövész Validátor
    Egyedi, célzott Google Text Search hívások a meglévő szervizek pontosítására.
    """
    PLACES_TEXT_URL = "https://places.googleapis.com/v1/places:searchText"
    
    def __init__(self):
        self.api_key = os.getenv("GOOGLE_API_KEY")
        # Napi limit: pl. 100 lekérdezés = kb. $3/nap maximum!
        self.daily_limit = int(os.getenv("GOOGLE_DAILY_LIMIT", "100"))
        self.quota = QuotaManager("google_places", self.daily_limit)
        self.headers = {
            "Content-Type": "application/json",
            "X-Goog-Api-Key": self.api_key,
            # Csak a legszükségesebb mezőket kérjük, hogy olcsó maradjon az API hívás!
            "X-Goog-FieldMask": "places.id,places.location,places.rating,places.userRatingCount,places.regularOpeningHours,places.internationalPhoneNumber,places.websiteUri"
        }

    async def fetch_place_details(self, client: httpx.AsyncClient, name: str, bio_context: str):
        if not self.api_key:
            logger.error("❌ HIÁNYZIK A GOOGLE_API_KEY a .env fájlból!")
            return None

        # A keresési kifejezés: pl. "Kovács Autószerviz Budapest"
        query_text = f"{name} {bio_context}"
        payload = {"textQuery": query_text, "maxResultCount": 1}

        for attempt in range(2):
            try:
                resp = await client.post(self.PLACES_TEXT_URL, json=payload, headers=self.headers)
                if resp.status_code == 200:
                    places = resp.json().get("places", [])
                    return places[0] if places else "NOT_FOUND"
                elif resp.status_code == 429:
                    await asyncio.sleep(2)
                else:
                    logger.error(f"Google API hiba: {resp.status_code}")
                    return None
            except Exception as e:
                logger.debug(f"Hálózati hiba a Google felé: {e}")
                await asyncio.sleep(1)
        return None

    async def validate_service(self, db, profile_id: int, fingerprint: str, bio: str):
        logger.info(f"📍 Validálás indul: {fingerprint}")
        
        if not self.quota.can_make_request():
            logger.warning("🛑 NAPI GOOGLE KVÓTA ELÉRVE! A Validátor holnapig alszik.")
            return "QUOTA_EXCEEDED"

        name = fingerprint.split('|')[0] if '|' in fingerprint else fingerprint
        
        async with httpx.AsyncClient(timeout=10.0) as client:
            place_data = await self.fetch_place_details(client, name, bio)

        try:
            if place_data == "NOT_FOUND":
                logger.warning(f"⚠️ A Google nem ismeri: {name}. Szellem szerviz?")
                await db.execute(
                    update(ServiceProfile)
                    .where(ServiceProfile.id == profile_id)
                    .values(status=ServiceStatus.ghost, last_audit_at=func.now())
                )
            elif place_data:
                # Kinyerjük a pontos GPS koordinátákat
                loc = place_data.get("location", {})
                lat, lon = loc.get("latitude"), loc.get("longitude")
                
                # Összeállítjuk az adatokat
                updates = {
                    "google_place_id": place_data.get("id"),
                    "rating": place_data.get("rating"),
                    "user_ratings_total": place_data.get("userRatingCount"),
                    "contact_phone": place_data.get("internationalPhoneNumber"),
                    "website": place_data.get("websiteUri"),
                    "opening_hours": place_data.get("regularOpeningHours", {}),
                    "is_verified": True,
                    "status": ServiceStatus.active,
                    "trust_score": ServiceProfile.trust_score + 50, # A Google megerősítette!
                    "last_audit_at": func.now()
                }

                # PostGIS Geometry frissítése, ha van GPS!
                if lat and lon:
                    logger.info(f"🗺️ Pontos koordináta megvan: {lat}, {lon}")
                    updates["location"] = func.ST_SetSRID(func.ST_MakePoint(lon, lat), 4326)

                await db.execute(
                    update(ServiceProfile)
                    .where(ServiceProfile.id == profile_id)
                    .values(**updates)
                )
                logger.info(f"✅ Szerviz hitelesítve és GPS pozicionálva: {name}")
            else:
                # API Hiba, később újra próbáljuk
                return "ERROR"
            
            await db.commit()
            return "DONE"
            
        except Exception as e:
            await db.rollback()
            logger.error(f"🚨 Adatbázis hiba a validálásnál: {e}")
            return "ERROR"

    @classmethod
    async def run(cls):
        self_instance = cls()
        logger.info("🎯 Service Validator (Robot-4) ONLINE - Várakozás dúsított szervizekre...")
        
        while True:
            try:
                async with AsyncSessionLocal() as db:
                    # ATOMI ZÁROLÁS: Keresünk egy aktív, de még nem validált szervizt
                    query = text("""
                        UPDATE marketplace.service_profiles
                        SET status = 'validation_in_progress'
                        WHERE id = (
                            SELECT id FROM marketplace.service_profiles
                            WHERE is_verified = false
                              AND status NOT IN ('validation_in_progress', 'ghost')
                            FOR UPDATE SKIP LOCKED
                            LIMIT 1
                        )
                        RETURNING id, fingerprint, bio;
                    """)
                    
                    result = await db.execute(query)
                    task = result.fetchone()
                    await db.commit()

                if task:
                    p_id, fprint, bio = task
                    async with AsyncSessionLocal() as process_db:
                        status = await self_instance.validate_service(process_db, p_id, fprint, bio)
                        
                        # Ha API hiba volt, visszaállítjuk az eredeti állapotot
                        if status == "ERROR":
                            await process_db.execute(text("UPDATE marketplace.service_profiles SET status = 'active' WHERE id = :id"), {"id": p_id})
                            await process_db.commit()
                            
                    if status == "QUOTA_EXCEEDED":
                        await asyncio.sleep(3600) # Elalszik 1 órára, ha kimerült a napi limit
                    else:
                        await asyncio.sleep(1) # Rate limit védelem
                else:
                    await asyncio.sleep(30) # Nincs új szerviz
                    
            except Exception as e:
                logger.error(f"💀 Kritikus hiba a Validator főciklusban: {e}")
                await asyncio.sleep(10)

if __name__ == "__main__":
    asyncio.run(GoogleValidator().run())