"""HTTP/HTTPS request and response analysis."""
import asyncio
from typing import Dict, Optional

import aiohttp

from reclaimor.config import Config
from reclaimor.utils.logger import setup_logger

logger = setup_logger(__name__)


class HTTPChecker:
    """HTTP/HTTPS response analysis."""
    
    def __init__(self, config: Config):
        self.config = config
    
    async def check(self, domain: str, session: aiohttp.ClientSession) -> Dict:
        """
        Perform HTTP checks on domain.
        
        Returns dict with:
            - status_code: int or None
            - body: str
            - headers: dict
            - redirect_chain: list
            - error: str or None
        """
        result = {
            "status_code": None,
            "body": "",
            "headers": {},
            "redirect_chain": [],
            "error": None,
        }
        
        # Try HTTPS first, then HTTP
        for scheme in ["https", "http"]:
            url = f"{scheme}://{domain}"
            try:
                async with session.get(
                    url,
                    allow_redirects=True,
                    ssl=False,  # Don't verify SSL for takeover detection
                ) as response:
                    result["status_code"] = response.status
                    result["headers"] = dict(response.headers)
                    
                    # Read body (limit size)
                    body = await response.text()
                    result["body"] = body[:5000]  # Limit to 5KB
                    
                    # Track redirects
                    if response.history:
                        result["redirect_chain"] = [
                            str(r.url) for r in response.history
                        ]
                    
                    return result
            
            except aiohttp.ClientError as e:
                logger.debug(f"HTTP error for {url}: {e}")
                result["error"] = str(e)
            except asyncio.TimeoutError:
                logger.debug(f"Timeout for {url}")
                result["error"] = "Timeout"
            except Exception as e:
                logger.debug(f"Unexpected error for {url}: {e}")
                result["error"] = str(e)
        
        return result
