"""Claude Haiku 일괄 카드가치 판단. 실패/미설정 시 빈 dict (graceful)."""
from __future__ import annotations

import json
import logging
import re
from typing import Any, Dict, List

from anthropic import Anthropic

from .config import ANTHROPIC_API_KEY, ANTHROPIC_MODEL_HAIKU

logger = logging.getLogger(__name__)

PROMPT = """다음 인스타 카드뉴스 후보 키워드들을 카드로 만들 가치(흥미·시의성·정보성)와
리스크(민감·논란)를 종합해 0~1 점수로 평가해라. 코드펜스 없이 JSON 배열로만 출력:
[{{"keyword_id": <id>, "score": <0~1>}}, ...]

후보:
{items}"""


def _strip_codefence(s: str) -> str:
    s = s.strip()
    if s.startswith("```"):
        s = re.sub(r"^```(?:json)?\s*|\s*```$", "", s).strip()
    return s


def parse_judge_response(raw: str) -> Dict[int, float]:
    try:
        data = json.loads(_strip_codefence(raw))
        return {int(d["keyword_id"]): float(d["score"]) for d in data}
    except Exception:
        logger.warning("judge 응답 파싱 실패")
        return {}


def judge_candidates(candidates: List[Dict[str, Any]]) -> Dict[int, float]:
    if not ANTHROPIC_API_KEY or not candidates:
        return {}
    items = "\n".join(f'- id={c["id"]}: {c["keyword"]} ({c["category"]})' for c in candidates)
    try:
        client = Anthropic(api_key=ANTHROPIC_API_KEY)
        resp = client.messages.create(
            model=ANTHROPIC_MODEL_HAIKU, max_tokens=1024,
            messages=[{"role": "user", "content": PROMPT.format(items=items)}],
        )
        return parse_judge_response(resp.content[0].text)
    except Exception:
        logger.exception("judge_candidates 호출 실패")
        return {}
