"""
Data models for progressive search functionality.
"""

from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum
from pathlib import Path
from typing import List, Optional, Dict, Any


class SearchStatus(Enum):
    """Search task status."""
    PENDING = "pending"
    IN_PROGRESS = "in_progress"
    COMPLETED = "completed"
    PAUSED = "paused"


@dataclass
class SearchConfig:
    """Configuration for progressive search."""
    
    # Search parameters
    target_directory: str
    max_files_per_session: int = 1000
    max_depth: int = 5
    
    # File type filters
    document_extensions: List[str] = field(default_factory=lambda: [
        ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", 
        ".pdf", ".txt", ".csv", ".rtf"
    ])
    
    key_extensions: List[str] = field(default_factory=lambda: [
        ".pem", ".ppk", ".key", ".gpg", ".p12", ".pfx", 
        ".jks", ".keystore", ".crt", ".cer"
    ])
    
    config_extensions: List[str] = field(default_factory=lambda: [
        ".env", ".config", ".json", ".xml", ".yaml", ".yml", 
        ".ini", ".properties", ".conf", ".cfg"
    ])
    
    archive_extensions: List[str] = field(default_factory=lambda: [
        ".zip", ".rar", ".7z", ".tar", ".gz", ".bz2"
    ])
    
    wallet_extensions: List[str] = field(default_factory=lambda: [
        ".wallet", ".dat", ".wal"
    ])
    
    # Keyword filters
    sensitive_keywords: List[str] = field(default_factory=lambda: [
        "password", "passwd", "secret", "confidential", "private",
        "credential", "key", "token", "auth", "api_key", "apikey",
        "ssh", "rsa", "dsa", "ecdsa", "ed25519",
        "wallet", "backup", "export", "dump"
    ])
    
    # Time-based filters
    min_file_size: int = 0  # bytes
    max_file_size: int = 100 * 1024 * 1024  # 100MB
    
    # Search scope
    include_hidden_files: bool = True
    follow_symlinks: bool = False


@dataclass
class SearchResult:
    """Individual search result."""
    
    file_path: str
    file_name: str
    file_size: int
    file_extension: str
    last_modified: datetime
    
    # Classification
    file_type: str  # "document", "key", "config", "archive", "wallet"
    matched_keywords: List[str] = field(default_factory=list)
    
    # Risk assessment
    risk_score: float = 0.0
    confidence: float = 0.0
    
    # Metadata
    scan_timestamp: datetime = field(default_factory=datetime.now)


@dataclass
class DirectoryState:
    """State of directory traversal."""
    
    directory_path: str
    depth: int
    status: str = "pending"  # pending, scanning, completed
    files_scanned: int = 0
    total_files: int = 0
    last_scan_time: Optional[datetime] = None


@dataclass
class SearchState:
    """State of progressive search session."""
    
    # Session identification
    session_id: str
    task_name: str
    
    # Search status
    status: SearchStatus = SearchStatus.PENDING
    start_time: Optional[datetime] = None
    end_time: Optional[datetime] = None
    
    # Progress tracking
    total_files_scanned: int = 0
    total_files_found: int = 0
    total_directories_scanned: int = 0
    total_directories: int = 0
    
    # Directory traversal state
    current_directory: Optional[str] = None
    scanned_directories: Dict[str, DirectoryState] = field(default_factory=dict)
    pending_directories: List[str] = field(default_factory=list)
    completed_directories: List[str] = field(default_factory=list)
    
    # File tracking
    scanned_files: List[str] = field(default_factory=list)
    
    # Results
    search_results: List[SearchResult] = field(default_factory=list)
    
    # Configuration
    config: SearchConfig = field(default_factory=SearchConfig)
    
    # Session metadata
    created_at: datetime = field(default_factory=datetime.now)
    updated_at: datetime = field(default_factory=datetime.now)
    
    def update_progress(self, files_scanned: int = 0, files_found: int = 0, directories_scanned: int = 0):
        """Update search progress metrics."""
        self.total_files_scanned += files_scanned
        self.total_files_found += files_found
        self.total_directories_scanned += directories_scanned
        self.updated_at = datetime.now()
    
    def add_scanned_file(self, file_path: str):
        """Add a file to the scanned files list."""
        if file_path not in self.scanned_files:
            self.scanned_files.append(file_path)
    
    def add_result(self, result: SearchResult):
        """Add a search result."""
        self.search_results.append(result)
        self.total_files_found += 1
        self.updated_at = datetime.now()
    
    def get_progress_percentage(self) -> float:
        """Get search progress percentage."""
        if self.total_directories == 0:
            return 0.0
        return (self.total_directories_scanned / self.total_directories) * 100
    
    def is_complete(self) -> bool:
        """Check if search is complete."""
        return len(self.pending_directories) == 0 and len(self.scanned_directories) > 0