# pyright: reportImportCycles=false
# Lazy (function-local) imports still count as static edges in basedpyright's
# reportImportCycles, so the ServiceRegistry singleton pattern necessarily forms
# import cycles. Breaking them would require an architectural refactor.
import logging
from typing import List

from ..utils.models import LoraMetadata
from .model_scanner import ModelScanner
import sys

logger = logging.getLogger(__name__)

class LoraScanner(ModelScanner):
    """Service for scanning and managing LoRA files"""
    
    def __init__(self):
        # Define supported file extensions
        file_extensions = {'.safetensors'}

        # Initialize parent class with ModelHashIndex
        from .model_hash_index import ModelHashIndex

        super().__init__(
            model_type="lora",
            model_class=LoraMetadata, 
            file_extensions=file_extensions,
            hash_index=ModelHashIndex()  # Changed from LoraHashIndex to ModelHashIndex
        )
    
    def get_model_roots(self) -> List[str]:
        """Get lora root directories (including extra paths)"""
        from ..config import config

        roots: List[str] = []
        roots.extend(config.loras_roots or [])
        roots.extend(config.extra_loras_roots or [])
        # Remove duplicates while preserving order
        seen: set[str] = set()
        unique_roots: List[str] = []
        for root in roots:
            if root and root not in seen:
                seen.add(root)
                unique_roots.append(root)
        return unique_roots

    async def diagnose_hash_index(self):
        """Diagnostic method to verify hash index functionality"""
        logger.debug("\n\n*** DIAGNOSING LORA HASH INDEX ***\n\n")
        
        # First check if the hash index has any entries
        if hasattr(self, '_hash_index'):
            index_entries = len(self._hash_index._hash_to_path)
            logger.debug(f"Hash index has {index_entries} entries")
            
            # Print a few example entries if available
            if index_entries > 0:
                logger.debug("\nSample hash index entries:")
                count = 0
                for hash_val, path in self._hash_index._hash_to_path.items():
                    if count < 5:  # Just show the first 5
                        logger.debug(f"Hash: {hash_val[:8]}... -> Path: {path}")
                        count += 1
                    else:
                        break
        else:
            logger.debug("Hash index not initialized")
        
        # Try looking up by a known hash for testing
        if not hasattr(self, '_hash_index') or not self._hash_index._hash_to_path:
            logger.debug("No hash entries to test lookup with")
            return
        
        test_hash = next(iter(self._hash_index._hash_to_path.keys()))
        test_path = self._hash_index.get_path(test_hash)
        logger.debug(f"\nTest lookup by hash: {test_hash[:8]}... -> {test_path}")
        if test_path is None:
            return
        
        # Also test reverse lookup
        test_hash_result = self._hash_index.get_hash(test_path)
        if test_hash_result is None:
            return
        logger.debug(f"Test reverse lookup: {test_path} -> {test_hash_result[:8]}...\n\n")

