"""
Adaptateur pour intégrer EnrichedScreenState avec le système de workflows existant.
Assure la compatibilité arrière complète en Phase 1 (Mode Light).
"""

from typing import Optional, Dict, Any
import numpy as np
from datetime import datetime

from .ui_element_models import EnrichedScreenState, WindowInfo
from .screen_state_manager import ScreenStateManager
from .workflow_detector import WorkflowStep
from .logger import Logger


class WorkflowStateAdapter:
    """
    Adaptateur pour convertir entre WorkflowStep (ancien) et EnrichedScreenState (nouveau).
    
    En Phase 1 (Mode Light):
    - Convertit les WorkflowStep existants en EnrichedScreenState
    - Maintient la compatibilité avec le système de workflows existant
    - Permet une migration progressive sans casser les workflows existants
    """
    
    def __init__(
        self,
        screen_state_manager: ScreenStateManager,
        logger: Logger
    ):
        """
        Initialise l'adaptateur.
        
        Args:
            screen_state_manager: Gestionnaire d'états d'écran
            logger: Logger pour journalisation
        """
        self.screen_state_manager = screen_state_manager
        self.logger = logger
    
    def workflow_step_to_screen_state(
        self,
        step: WorkflowStep,
        session_id: str,
        screenshot_path: str,
        screen_resolution: tuple = (1920, 1080)
    ) -> EnrichedScreenState:
        """
        Convertit un WorkflowStep en EnrichedScreenState.
        
        Args:
            step: WorkflowStep à convertir
            session_id: ID de session
            screenshot_path: Chemin vers le screenshot
            screen_resolution: Résolution d'écran
            
        Returns:
            EnrichedScreenState créé
        """
        # Extraire les informations du WorkflowStep
        app_name = step.window.split(" - ")[0] if " - " in step.window else step.window
        window_title = step.window
        
        # Créer l'EnrichedScreenState
        screen_state = self.screen_state_manager.create_screen_state(
            session_id=session_id,
            window_title=window_title,
            app_name=app_name,
            screenshot_path=screenshot_path,
            screen_resolution=screen_resolution,
            embedding_provider="legacy_workflow_step",
            detected_text=[step.target_description] if step.target_description else [],
            context_tags=[step.action_type]
        )
        
        self.logger.log_action({
            "action": "workflow_step_converted",
            "step_id": step.step_id,
            "screen_state_id": screen_state.screen_state_id
        })
        
        return screen_state
    
    def screen_state_to_workflow_step(
        self,
        screen_state: EnrichedScreenState,
        step_id: int,
        action_type: str = "unknown",
        position: tuple = (0, 0)
    ) -> WorkflowStep:
        """
        Convertit un EnrichedScreenState en WorkflowStep (pour compatibilité).
        
        Args:
            screen_state: EnrichedScreenState à convertir
            step_id: ID de l'étape
            action_type: Type d'action
            position: Position de l'action
            
        Returns:
            WorkflowStep créé
        """
        # Extraire les informations de l'EnrichedScreenState
        target_description = " ".join(screen_state.perception.detected_text[:3])  # Premiers 3 mots
        
        # Créer le WorkflowStep
        step = WorkflowStep(
            step_id=step_id,
            action_type=action_type,
            target_description=target_description,
            position=position,
            window=screen_state.window.window_title,
            embedding=None,  # Sera chargé séparément si nécessaire
            screenshot=None  # Sera chargé séparément si nécessaire
        )
        
        self.logger.log_action({
            "action": "screen_state_converted",
            "screen_state_id": screen_state.screen_state_id,
            "step_id": step_id
        })
        
        return step
    
    def save_workflow_with_screen_states(
        self,
        workflow_id: str,
        steps: list,
        session_id: str
    ) -> list:
        """
        Sauvegarde un workflow en créant des EnrichedScreenState pour chaque étape.
        
        Args:
            workflow_id: ID du workflow
            steps: Liste de WorkflowStep
            session_id: ID de session
            
        Returns:
            Liste des screen_state_id créés
        """
        screen_state_ids = []
        
        for i, step in enumerate(steps):
            # Créer un chemin de screenshot (peut être None si pas de screenshot)
            screenshot_path = f"data/workflows/{workflow_id}/step_{i}.png"
            
            # Convertir en EnrichedScreenState
            screen_state = self.workflow_step_to_screen_state(
                step=step,
                session_id=session_id,
                screenshot_path=screenshot_path
            )
            
            # Sauvegarder
            embedding_vector = step.embedding if step.embedding is not None else None
            self.screen_state_manager.save_screen_state(
                screen_state,
                save_embedding=(embedding_vector is not None),
                embedding_vector=embedding_vector
            )
            
            screen_state_ids.append(screen_state.screen_state_id)
        
        self.logger.log_action({
            "action": "workflow_saved_with_screen_states",
            "workflow_id": workflow_id,
            "steps_count": len(steps),
            "screen_states_created": len(screen_state_ids)
        })
        
        return screen_state_ids


if __name__ == "__main__":
    # Tests basiques
    from .logger import Logger
    from .workflow_detector import WorkflowStep
    import shutil
    from pathlib import Path
    
    print("Test du WorkflowStateAdapter")
    print("=" * 50)
    
    # Créer un logger de test
    logger = Logger(log_dir="test_logs")
    
    # Créer le manager et l'adaptateur
    manager = ScreenStateManager(
        logger=logger,
        data_dir="test_data",
        mode="light"
    )
    
    adapter = WorkflowStateAdapter(
        screen_state_manager=manager,
        logger=logger
    )
    
    print("\n1. Test conversion WorkflowStep → EnrichedScreenState:")
    # Créer un WorkflowStep de test
    step = WorkflowStep(
        step_id=1,
        action_type="click",
        target_description="Valider Button",
        position=(100, 200),
        window="Test App - Main Window",
        embedding=np.random.rand(512),
        screenshot=None
    )
    
    screen_state = adapter.workflow_step_to_screen_state(
        step=step,
        session_id="test_session",
        screenshot_path="test_data/screens/step_1.png"
    )
    
    print(f"   Screen State ID: {screen_state.screen_state_id}")
    print(f"   Window Title: {screen_state.window.window_title}")
    print(f"   Detected Text: {screen_state.perception.detected_text}")
    
    print("\n2. Test conversion EnrichedScreenState → WorkflowStep:")
    converted_step = adapter.screen_state_to_workflow_step(
        screen_state=screen_state,
        step_id=1,
        action_type="click",
        position=(100, 200)
    )
    
    print(f"   Step ID: {converted_step.step_id}")
    print(f"   Action Type: {converted_step.action_type}")
    print(f"   Target: {converted_step.target_description}")
    print(f"   Window: {converted_step.window}")
    
    print("\n3. Test sauvegarde de workflow avec screen states:")
    steps = [step]
    screen_state_ids = adapter.save_workflow_with_screen_states(
        workflow_id="test_workflow_001",
        steps=steps,
        session_id="test_session"
    )
    
    print(f"   Created {len(screen_state_ids)} screen states")
    print(f"   Screen State IDs: {screen_state_ids}")
    
    print("\n✓ Tous les tests WorkflowStateAdapter réussis!")
    
    # Nettoyage
    if Path("test_data").exists():
        shutil.rmtree("test_data")
    if Path("test_logs").exists():
        shutil.rmtree("test_logs")
