"""Fingerprint loader and manager."""
import json
from pathlib import Path
from typing import List, Dict

from reclaimor.utils.logger import setup_logger

logger = setup_logger(__name__)


class FingerprintLoader:
    """Load and manage provider fingerprints."""
    
    def __init__(self, fingerprints_dir: Path):
        self.fingerprints_dir = Path(fingerprints_dir)
    
    def load(self) -> List[Dict]:
        """Load all fingerprints from directory."""
        fingerprints = []
        
        if not self.fingerprints_dir.exists():
            logger.warning(f"Fingerprints directory not found: {self.fingerprints_dir}")
            return fingerprints
        
        for fp_file in self.fingerprints_dir.glob("*.json"):
            try:
                with open(fp_file, "r") as f:
                    data = json.load(f)
                    
                    # Support both single fingerprint and array
                    if isinstance(data, list):
                        fingerprints.extend(data)
                    else:
                        fingerprints.append(data)
                
                logger.debug(f"Loaded fingerprints from {fp_file.name}")
            
            except Exception as e:
                logger.error(f"Error loading {fp_file}: {e}")
        
        logger.info(f"Loaded {len(fingerprints)} fingerprints")
        return fingerprints
    
    def add_fingerprint(self, fingerprint: Dict, filename: str = "custom.json"):
        """Add a new fingerprint to the collection."""
        filepath = self.fingerprints_dir / filename
        
        existing = []
        if filepath.exists():
            with open(filepath, "r") as f:
                existing = json.load(f)
        
        existing.append(fingerprint)
        
        with open(filepath, "w") as f:
            json.dump(existing, f, indent=2)
        
        logger.info(f"Added fingerprint to {filename}")
