#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Kiểm thử tích hợp Muse2API Gateway vào Pipeline Thập Ngũ Niên
"""

import os
import sys
from pathlib import Path
import pytest

PIPELINE_DIR = Path(__file__).resolve().parent.parent / "05_Production_Pipeline"
if str(PIPELINE_DIR) not in sys.path:
    sys.path.insert(0, str(PIPELINE_DIR))

from muse_api_client import (
    MuseApiClient,
    resolve_api_key,
    sanitize_prompt,
    ensure_audio_guard,
    encode_image_to_data_uri,
    AUDIO_GUARD_CANONICAL
)
from run_shot import classify_shot_engine


def test_muse_api_key_resolution():
    key = resolve_api_key()
    assert key is not None
    assert len(key) > 10


def test_audio_guard_canonical():
    prompt = "Cảnh Thúy Kiều trầm tư bên song cửa"
    guarded = ensure_audio_guard(prompt)
    assert AUDIO_GUARD_CANONICAL.strip() in guarded
    assert "no music/BGM" in guarded


def test_prompt_sanitization():
    raw = "Thúy Kiều đứng trước nấm mồ cô quạnh đầy âm khí bạc mệnh"
    cleaned = sanitize_prompt(raw)
    assert "nấm mồ" not in cleaned
    assert "âm khí" not in cleaned
    assert "gò đất phủ cỏ úa" in cleaned


def test_gateway_health():
    client = MuseApiClient()
    assert client.is_available() is True
    health = client.check_health()
    assert health.get("ready") is True
    assert "accounts" in health
    assert health["accounts"]["total"] >= 1


def test_classify_shot_engine_routing():
    assert classify_shot_engine("shot_close", prompt="Cận cảnh giọt lệ Thúy Kiều") == "gradio_ltx"
    assert classify_shot_engine("shot_wide", prompt="Toàn cảnh kinh thành nhộn nhịp") in ("muse", "muse_api")


if __name__ == "__main__":
    pytest.main([__file__, "-v"])
