import os
import asyncio
import re
from database.connection import get_connection
from core.asset_generator import AssetGenerator

class PhraseManager:
    def __init__(self):
        self.asset_gen = AssetGenerator()

    def _clean_filename(self, text: str) -> str:
        """Filters forbidden system characters but preserves Spanish diacritics."""
        safe_text = re.sub(r'[/\\?%*:|"<>]', '', text)
        return safe_text.strip().replace(" ", "_")

    async def add_translation_pair(self, spanish_text: str, english_text: str, 
                                   textbook: str = None, unit: int = None, 
                                   context: str = None, voice_gender: str = "male"):
        """
        Takes a multi-lingual pair, automates audio generation, 
        and securely links them together in the SQLite database.
        """
        conn = get_connection()
        cursor = conn.cursor()
        
        try:
            # 1. Insert Spanish Phrase Row
            cursor.execute("""
                INSERT INTO phrases (text, language, textbook, unit, source_context)
                VALUES (?, 'es', ?, ?, ?)
            """, (spanish_text, textbook, unit, context))
            es_id = cursor.lastrowid

            # 2. Insert English Phrase Row
            cursor.execute("""
                INSERT INTO phrases (text, language, textbook, unit, source_context)
                VALUES (?, 'en', ?, ?, ?)
            """, (english_text, textbook, unit, context))
            en_id = cursor.lastrowid

            # 3. Create Bidirectional Translation Bridges
            cursor.execute("INSERT INTO translations (source_phrase_id, target_phrase_id) VALUES (?, ?)", (es_id, en_id))
            cursor.execute("INSERT INTO translations (source_phrase_id, target_phrase_id) VALUES (?, ?)", (en_id, es_id))

            # 4. Automate Castilian Audio Generation
            safe_filename = self._clean_filename(spanish_text)
            audio_filename = f"{safe_filename}_{voice_gender}.mp3"
            output_path = os.path.join("media", audio_filename)
            
            # Fire our cloud TTS utility
            await self.asset_gen.generate_speech(spanish_text, output_path, gender=voice_gender)
            selected_voice_name = self.asset_gen.voices.get(voice_gender.lower(), "es-ES-AlvaroNeural")

            # 5. Log Audio Track to Database
            cursor.execute("""
                INSERT INTO audio_tracks (phrase_id, voice_gender, voice_name, file_path, is_reference)
                VALUES (?, ?, ?, ?, 1)
            """, (es_id, voice_gender.lower(), selected_voice_name, output_path))

            # Commit everything at once securely
            conn.commit()
            print(f"✨ Successfully integrated: '{spanish_text}' ⇄ '{english_text}'")
            print(f"   Audio generated safely at: {output_path}")
            return True

        except Exception as e:
            conn.rollback()
            print(f"❌ Error during phrase ingestion transaction: {e}")
            return False
        finally:
            conn.close()