"""
JavaScript Download Module
"""

import requests
from pathlib import Path
from typing import List, Dict
from urllib.parse import urlparse
import hashlib

from ..utils.logger import log_progress
from ..utils.fs import ensure_dir

class JSDownloader:
    """Download JavaScript files"""
    
    def __init__(self, output_dir: Path):
        self.output_dir = output_dir
        self.js_dir = output_dir / "js_files"
        ensure_dir(self.js_dir)
        
        self.session = requests.Session()
        self.session.headers.update({
            'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
        })
    
    def download_js_file(self, url: str) -> Dict:
        """Download a single JavaScript file"""
        try:
            response = self.session.get(url, timeout=30)
            response.raise_for_status()
            
            # Generate filename from URL hash
            url_hash = hashlib.md5(url.encode()).hexdigest()[:8]
            parsed = urlparse(url)
            domain = parsed.netloc.replace('.', '_')
            filename = f"{domain}_{url_hash}.js"
            
            filepath = self.js_dir / filename
            
            with open(filepath, 'w', encoding='utf-8', errors='ignore') as f:
                f.write(response.text)
            
            return {
                'url': url,
                'filepath': str(filepath),
                'size': len(response.text),
                'status': 'success'
            }
            
        except Exception as e:
            return {
                'url': url,
                'filepath': None,
                'size': 0,
                'status': 'failed',
                'error': str(e)
            }
    
    def download_js_files(self, urls: List[str], max_files: int = 100) -> List[Dict]:
        """Download multiple JavaScript files"""
        log_progress(f"Downloading JavaScript files (max {max_files})")
        
        # Limit number of files to download
        urls_to_download = urls[:max_files]
        
        results = []
        successful = 0
        
        for i, url in enumerate(urls_to_download, 1):
            if i % 10 == 0:
                log_progress(f"Downloaded {i}/{len(urls_to_download)} files")
            
            result = self.download_js_file(url)
            results.append(result)
            
            if result['status'] == 'success':
                successful += 1
        
        log_progress(f"Successfully downloaded {successful}/{len(urls_to_download)} JavaScript files")
        
        return results