import os
import json
from typing import List, Dict, Any, Optional
from agents.base_agent import BaseAgent

class Orchestrator:
    def __init__(self, 
                 output_dir: str = "output/", 
                 json_agent: Optional[BaseAgent] = None,
                 image_sorter: Optional[BaseAgent] = None,
                 image_analyser: Optional[BaseAgent] = None,
                 report_generator: Optional[BaseAgent] = None):
        
        self.output_dir = output_dir
        
        # Assignation directe des agents (qui peuvent être injectés lors des tests)
        self.json_agent = json_agent
        self.image_sorter = image_sorter
        self.image_analyser = image_analyser
        self.report_generator = report_generator

    def detecter_tickets(self) -> List[str]:
        tickets = []
        for ticket_dir in os.listdir(self.output_dir):
            ticket_path = os.path.join(self.output_dir, ticket_dir)
            if os.path.isdir(ticket_path) and ticket_dir.startswith("ticket_"):
                tickets.append(ticket_path)
        return tickets

    def traiter_ticket(self, ticket_path: str):
        for extraction in os.listdir(ticket_path):
            extraction_path = os.path.join(ticket_path, extraction)
            if os.path.isdir(extraction_path):
                attachments_dir = os.path.join(extraction_path, "attachments")
                rapport_json_path = os.path.join(extraction_path, f"{extraction.split('_')[0]}_rapport.json")
                rapports_dir = os.path.join(extraction_path, f"{extraction.split('_')[0]}_rapports")

                os.makedirs(rapports_dir, exist_ok=True)

                if os.path.exists(rapport_json_path):
                    with open(rapport_json_path, 'r', encoding='utf-8') as file:
                        ticket_json = json.load(file)

                    json_analysis = self.json_agent.executer(ticket_json) if self.json_agent else None

                    relevant_images = []
                    if os.path.exists(attachments_dir):
                        for attachment in os.listdir(attachments_dir):
                            attachment_path = os.path.join(attachments_dir, attachment)
                            if attachment.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif')):
                                is_relevant = self.image_sorter.executer(attachment_path) if self.image_sorter else False
                                if is_relevant:
                                    relevant_images.append(attachment_path)

                    image_analysis_results = {}
                    for image_path in relevant_images:
                        if self.image_analyser and json_analysis:
                            image_analysis_results[image_path] = self.image_analyser.executer(
                                image_path, 
                                contexte=json_analysis
                            )

                    rapport_data = {
                        "analyse_json": json_analysis,
                        "analyse_images": image_analysis_results
                    }
                    if self.report_generator:
                        self.report_generator.executer(rapport_data, os.path.join(rapports_dir, extraction.split('_')[0]))

                    print(f"Traitement du ticket {ticket_path} terminé.\n")

    def executer(self):
        tickets = self.detecter_tickets()
        for ticket in tickets:
            self.traiter_ticket(ticket)
