"""SP-6 sync helpers forward — NAS → Windows music-render.

NAS music-lab의 /api/music/lyrics, /api/music/credits,
/api/music/timestamped-lyrics, /api/music/style-boost 호출을
Windows music-render의 /api/music-render/sync/* 로 forward.

SUNO_API_KEY는 NAS에 없으므로 NAS에서 직접 호출 불가.
"""
from __future__ import annotations

import logging
import os
from typing import Optional

import httpx

logger = logging.getLogger(__name__)

MUSIC_RENDER_URL = os.getenv("MUSIC_RENDER_URL", "http://192.168.45.59:18711")
_TIMEOUT = 60.0  # 가사 생성은 폴링 포함 ~45초


def forward_lyrics(prompt: str) -> Optional[dict]:
    try:
        r = httpx.post(
            f"{MUSIC_RENDER_URL}/api/music-render/sync/lyrics",
            json={"prompt": prompt},
            timeout=_TIMEOUT,
        )
        if r.status_code == 200:
            return r.json()
        logger.warning("forward_lyrics returned %d", r.status_code)
    except Exception:
        logger.exception("forward_lyrics 실패")
    return None


def forward_credits() -> Optional[dict]:
    try:
        r = httpx.get(
            f"{MUSIC_RENDER_URL}/api/music-render/sync/credits",
            timeout=30.0,
        )
        if r.status_code == 200:
            return r.json()
    except Exception:
        logger.exception("forward_credits 실패")
    return None


def forward_timestamped_lyrics(task_id: str, suno_id: str) -> Optional[dict]:
    try:
        r = httpx.get(
            f"{MUSIC_RENDER_URL}/api/music-render/sync/timestamped-lyrics",
            params={"task_id": task_id, "suno_id": suno_id},
            timeout=30.0,
        )
        if r.status_code == 200:
            return r.json()
    except Exception:
        logger.exception("forward_timestamped_lyrics 실패")
    return None


def forward_style_boost(content: str) -> Optional[dict]:
    try:
        r = httpx.post(
            f"{MUSIC_RENDER_URL}/api/music-render/sync/style-boost",
            json={"content": content},
            timeout=30.0,
        )
        if r.status_code == 200:
            return r.json()
    except Exception:
        logger.exception("forward_style_boost 실패")
    return None
