import json
from openai import OpenAI
from app.config.secrets import OPENAI_API_KEY
from app.ai.prompts import SYSTEM_PROMPT, USER_PROMPT_TEMPLATE

client = OpenAI(api_key=OPENAI_API_KEY)

def analyze_article(title: str, excerpt: str, content: str = "", model: str = "gpt-4o-mini"):
    user_prompt = USER_PROMPT_TEMPLATE.format(
        title=(title or "").strip(),
        excerpt=(excerpt or "").strip(),
        content=(content or "").strip(),
    )

    resp = client.chat.completions.create(
        model=model,
        temperature=0.2,
        messages=[
            {"role": "system", "content": SYSTEM_PROMPT.strip()},
            {"role": "user", "content": user_prompt.strip()},
        ],
        response_format={"type": "json_object"},
    )

    content_resp = resp.choices[0].message.content.strip()

    usage = getattr(resp, "usage", None)
    tokens_in = getattr(usage, "prompt_tokens", None) if usage else None
    tokens_out = getattr(usage, "completion_tokens", None) if usage else None

    data = json.loads(content_resp)

    score = int(data.get("good_news_score", 0))
    score = max(0, min(100, score))

    summary = (data.get("summary") or "").strip()
    topic = (data.get("topic") or "").strip() or None

    wink = data.get("wink_title", None)
    wink = wink.strip() if isinstance(wink, str) and wink.strip() else None

    source_lang = (data.get("source_lang") or "unknown").strip()
    score_reason = (data.get("score_reason") or "").strip()

    return {
        "good_news_score": score,
        "summary": summary,
        "topic": topic,
        "wink_title": wink,
        "source_lang": source_lang,
        "score_reason": score_reason,
        "model": model,
        "tokens_in": tokens_in,
        "tokens_out": tokens_out,
    }