import os
import logging
from typing import Dict, Callable, Optional, List

logger = logging.getLogger(__name__)

class CertificateManager:
    """
    Manages local certificate files and updates.
    """
    def __init__(self, cert_dir: str, on_update_callback: Optional[Callable] = None):
        self.cert_dir = cert_dir
        self.on_update_callback = on_update_callback
        
        if not os.path.exists(self.cert_dir):
            os.makedirs(self.cert_dir, exist_ok=True)

    def update_certificates(self, domain: str, files_data: Dict[str, str]) -> bool:
        """
        Writes certificate files to the local directory.
        Returns True if files were updated.
        """
        domain_dir = os.path.join(self.cert_dir, domain)
        if not os.path.exists(domain_dir):
            os.makedirs(domain_dir, exist_ok=True)
            
        updated = False
        
        try:
            for filename, content in files_data.items():
                if not content:
                    continue
                    
                # Map API keys to standard filenames if needed, 
                # or assume keys are like 'fullchain', 'privkey', etc.
                # The API returns: "fullchain", "privkey", "cert", "chain"
                
                # We'll append .pem if missing
                fname = f"{filename}.pem" if not filename.endswith('.pem') else filename
                file_path = os.path.join(domain_dir, fname)
                
                # Check if content changed
                if os.path.exists(file_path):
                    with open(file_path, 'r') as f:
                        current_content = f.read()
                    if current_content == content:
                        continue
                
                # Write new content
                with open(file_path, 'w') as f:
                    f.write(content)
                
                # Secure private key
                if 'privkey' in filename:
                    os.chmod(file_path, 0o600)
                
                updated = True
                logger.info(f"Updated certificate file: {file_path}")
            
            if updated:
                logger.info(f"Certificates for {domain} updated successfully.")
                if self.on_update_callback:
                    logger.info("Executing update callback...")
                    try:
                        self.on_update_callback()
                        logger.info("Callback executed successfully.")
                    except Exception as e:
                        logger.error(f"Error executing callback: {e}")
            
            return updated
            
        except Exception as e:
            logger.error(f"Failed to update local certificates: {e}")
            raise

