"""Language mode routes."""

from fastapi import APIRouter
from fastapi.responses import JSONResponse
import globals
from utils.logger import get_logger

logger = get_logger('api')

router = APIRouter()


@router.get("/language")
def get_language_mode():
    """Get current language mode (english or japanese)"""
    return {
        "language_mode": globals.LANGUAGE_MODE,
        "available_languages": ["english", "japanese"],
        "current_model": globals.JAPANESE_TEXT_MODEL if globals.LANGUAGE_MODE == "japanese" else globals.TEXT_MODEL
    }


@router.post("/language/toggle")
def toggle_language_mode():
    """Toggle between English and Japanese modes"""
    if globals.LANGUAGE_MODE == "english":
        globals.LANGUAGE_MODE = "japanese"
        new_mode = "japanese"
        model_used = globals.JAPANESE_TEXT_MODEL
        logger.info("Switched to Japanese mode (using Llama 3.1 Swallow)")
    else:
        globals.LANGUAGE_MODE = "english"
        new_mode = "english"
        model_used = globals.TEXT_MODEL
        logger.info("Switched to English mode (using default model)")

    # Persist via config manager
    try:
        from config_manager import config_manager
        config_manager.set("discord.language_mode", new_mode, persist=True)
        logger.info(f"💾 Language mode persisted to config_runtime.yaml")
    except Exception as e:
        logger.warning(f"Failed to persist language mode: {e}")

    return {
        "status": "ok",
        "language_mode": new_mode,
        "model_now_using": model_used,
        "message": f"Miku is now speaking in {new_mode.upper()}!"
    }


@router.post("/language/set")
def set_language_mode(language: str = "english"):
    """Set language mode to either 'english' or 'japanese'"""
    if language.lower() not in ["english", "japanese"]:
        return JSONResponse(status_code=400, content={"status": "error", "message": f"Invalid language mode '{language}'. Use 'english' or 'japanese'."})

    globals.LANGUAGE_MODE = language.lower()
    model_used = globals.JAPANESE_TEXT_MODEL if language.lower() == "japanese" else globals.TEXT_MODEL
    logger.info(f"Language mode set to {language.lower()} (using {model_used})")

    # Persist so it survives restarts
    try:
        from config_manager import config_manager
        config_manager.set("discord.language_mode", language.lower(), persist=True)
    except Exception:
        pass

    return {
        "status": "ok",
        "language_mode": language.lower(),
        "model_now_using": model_used,
        "message": f"Miku is now speaking in {language.upper()}!"
    }
