#!/usr/bin/env python3

import os
import sys
import json
import argparse
from utils.auth_manager import AuthManager
from utils.ticket_manager import TicketManager
from utils.attachment_manager import AttachmentManager
from utils.message_manager import MessageManager
from utils.utils import save_json

def main():
    parser = argparse.ArgumentParser(description="Extraction de tickets Odoo")
    parser.add_argument("ticket_code", help="Code du ticket à extraire (ex: T0167)")
    parser.add_argument("--config", default="config.json", help="Chemin vers le fichier de configuration")
    parser.add_argument("--output-dir", help="Répertoire de sortie (par défaut: output/ticket_CODE)")
    parser.add_argument("--verbose", "-v", action="store_true", help="Afficher plus d'informations")
    args = parser.parse_args()
    
    # Charger la configuration
    try:
        with open(args.config, "r", encoding="utf-8") as f:
            config = json.load(f)
        
        if args.verbose:
            print(f"Configuration chargée depuis {args.config}")
    except Exception as e:
        print(f"Erreur lors du chargement de la configuration: {e}")
        sys.exit(1)
    
    # Extraire les informations de connexion
    odoo_config = config.get("odoo", {})
    url = odoo_config.get("url")
    db = odoo_config.get("db")
    username = odoo_config.get("username")
    api_key = odoo_config.get("api_key")
    
    if not all([url, db, username, api_key]):
        print("Informations de connexion Odoo manquantes dans le fichier de configuration")
        sys.exit(1)
    
    # Définir le répertoire de sortie
    output_dir = args.output_dir or os.path.join(config.get("output_dir", "output"), f"ticket_{args.ticket_code}")
    os.makedirs(output_dir, exist_ok=True)

    # Authentification Odoo
    auth = AuthManager(url, db, username, api_key)
    if not auth.login():
        print("Échec de connexion à Odoo")
        sys.exit(1)
    
    # Initialiser les gestionnaires
    ticket_manager = TicketManager(auth)
    attachment_manager = AttachmentManager(auth)
    message_manager = MessageManager(auth)
    
    # Récupérer le ticket
    ticket = ticket_manager.get_ticket_by_code(args.ticket_code)
    if not ticket:
        print(f"Ticket {args.ticket_code} non trouvé")
        sys.exit(1)

    ticket_id = ticket.get('id')
    
    # Sauvegarder ticket_info.json
    ticket_info_path = os.path.join(output_dir, "ticket_info.json")
    save_json(ticket, ticket_info_path)

    if args.verbose:
        print(f"Ticket {args.ticket_code} trouvé (ID: {ticket_id})")
        print(f"Extraction des données vers {output_dir}...")

    # Récupérer et sauvegarder les messages
    messages = message_manager.get_ticket_messages(ticket_id)
    all_messages_path = os.path.join(output_dir, "all_messages.json")
    save_json(messages, all_messages_path)
    
    # Récupérer et sauvegarder les pièces jointes
    attachments = attachment_manager.get_ticket_attachments(ticket_id)
    attachments_path = os.path.join(output_dir, "attachments_info.json")
    save_json(attachments, attachments_path)
    
    # Génération de structure.json
    structure = {
        "date_extraction": datetime.now().isoformat(),
        "ticket_dir": output_dir,
        "fichiers_json": [
            "ticket_info.json",
            "all_messages.json",
            "attachments_info.json"
        ]
    }
    structure_path = os.path.join(output_dir, "structure.json")
    save_json(structure, structure_path)

    print("Extraction terminée avec succès")
    print(f"- Informations du ticket: {ticket_info_path}")
    print(f"- Messages: {all_messages_path}")
    print(f"- Pièces jointes: {attachments_path}")
    print(f"- Structure: {structure_path}")

if __name__ == "__main__":
    main()
