import asyncio
import logging
from OTXv2 import OTXv2
from OTXv2 import IndicatorTypes
from .config import settings

logger = logging.getLogger(__name__)

class OtxScanner:
    """
    AlienVault OTX Scanner Integration
    Fetches threat intelligence data for domains, IPs, and hashes.
    """
    def __init__(self, api_key: str = None):
        # Prioritize passed key, fallback to environment variable
        self.api_key = api_key or settings.ALIENTVAULT_OTX_API_KEY
        self.otx = None
        
        if self.api_key:
            self.otx = OTXv2(self.api_key)
        else:
            logger.warning("AlienVault OTX API Key is missing. Scanner will not work.")

    def _scan_sync(self, domain: str) -> dict:
        """Synchronous blocking function to call OTX API."""
        if not self.otx:
            return {"success": False, "error": "API Key not configured."}
            
        try:
            # We use HOSTNAME as the default indicator type for domains
            result = self.otx.get_indicator_details_full(IndicatorTypes.HOSTNAME, domain)
            return {"success": True, "data": result}
        except Exception as e:
            logger.error(f"AlienVault OTX Scan Error: {str(e)}")
            return {"success": False, "error": str(e)}

    async def scan(self, domain: str) -> dict:
        """
        Asynchronous wrapper for the OTX scan.
        Runs the blocking requests library in a separate thread.
        """
        logger.info(f"Scanning domain on AlienVault OTX: {domain}")
        loop = asyncio.get_event_loop()
        # Run the synchronous function in a background thread to prevent blocking
        return await loop.run_in_executor(None, self._scan_sync, domain)