import os
import sys
import re
import traceback
import requests
from io import BytesIO
from dotenv import load_dotenv

load_dotenv()

try:
    sys.stdout.reconfigure(encoding="utf-8")
except Exception:
    pass


def normalize_sentence(sentence: str) -> str:
    # 28.4 -> 28
    sentence = re.sub(r"(\d+)[\.,]\d+", lambda m: m.group(1), sentence)
    # Fazla boşlukları toparla
    sentence = re.sub(r"\s+", " ", sentence).strip()
    # "derece" -> "santigrat derece"
    if "derece" in sentence and "santigrat" not in sentence:
        sentence = sentence.replace("derece", "santigrat derece")
    # UV harf harf okunsun
    sentence = re.sub(r"\bUV\b", "U V", sentence)
    return sentence


def create_voice(text: str) -> BytesIO:
    api_key = os.getenv("ELEVENLABS_API_KEY")
    if not api_key:
        raise RuntimeError("ELEVENLABS_API_KEY tanımlı değil.")

    voice_id = os.getenv("VOICE_ARKO") or os.getenv("VOICE_ID2")
    if not voice_id:
        raise RuntimeError("VOICE_ARKO / VOICE_ID2 tanımlı değil.")

    url = f"https://api.elevenlabs.io/v1/text-to-speech/xjlfQQ3ynqiEyRpArrT8"

    payload = {
        "text": text,
        "model_id": "eleven_v3",
        "languages": [{"language_id": "tr", "name": "Turkish"}],
        "voice_settings": {
            "stability": 0.6,
            "similarity_boost": 0.75,
            "style": 0.5,
            "speaker_boost": True,
            "speed": 0.9,
        },
        "pronunciation_guide": {
            "style": "sıcak, samimi ve yumuşak bakım reklamı seslendirmesi",
            "hints": (
                "Yumuşak ve güven veren bir tonla oku, satış yapar gibi değil sohbet eder gibi. "
                "Hava durumu cümlelerini akıcı ve doğal geç. "
                "'U V seviyesi' ifadesinde harfleri ayrı ayrı net söyle. "
                "'Bugün Glow zamanı' cümlesinde tonu hafif yükselt, kısa bir durak bırak. "
                "'Arko Nem, Ekstra Serum' ürün adını net ve vurgulu söyle, virgülde kısa dur. "
                "Son cümle 'Yakışır tabii cildime' gülümseyerek, kendinden emin ve sıcak bitsin."
            ),
        },
    }

    resp = requests.post(
        url,
        headers={"xi-api-key": api_key, "Content-Type": "application/json"},
        json=payload,
        timeout=60,
    )

    if resp.status_code >= 400:
        raise RuntimeError(f"ElevenLabs HTTP {resp.status_code}: {resp.text[:500]}")

    return BytesIO(resp.content)


def main():
    log_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), "arko_py.log")
    try:
        if len(sys.argv) < 3:
            raise ValueError("Kullanım: python arko.py <sentence> <output_path>")

        sentence = normalize_sentence(sys.argv[1])
        output_path = sys.argv[2]

        print(f"Metin: {sentence}")
        print(f"Çıkış: {output_path}")

        audio_stream = create_voice(sentence)

        out_dir = os.path.dirname(output_path)
        if out_dir:
            os.makedirs(out_dir, exist_ok=True)

        with open(output_path, "wb") as f:
            f.write(audio_stream.read())

        print(f"OK: Arko reklam sesi yazıldı -> {output_path}")
        sys.exit(0)

    except Exception as e:
        err = f"ERROR: {e}\n{traceback.format_exc()}"
        try:
            with open(log_file, "a", encoding="utf-8") as f:
                f.write("\n" + ("-" * 60) + "\n")
                f.write(err + "\n")
        except Exception:
            pass
        print(err)
        sys.exit(1)


if __name__ == "__main__":
    main()
