"""Optional: schlauere Antworten mit OPENAI_API_KEY."""

from __future__ import annotations

import os

from jam.brain import JamBrain


def _personality_block(brain: JamBrain) -> str:
    from jam.upbringing import ensure_traits

    s = brain.state
    ensure_traits(s)
    traits = ", ".join(f"{k} {v:.0%}" for k, v in s.traits.items())
    rules = "; ".join(
        f"wenn {r.get('trigger')} dann {r.get('behavior')}"
        for r in s.rules[-8:]
    )
    from jam.owner import owner_name

    return (
        f"Dein Mensch heißt {owner_name(s)}. Sprich ihn bei Fragen mit Namen an. "
        f"Persönlichkeit: {traits}. Disziplin {s.discipline:.0%}. "
        f"Erziehung: {s.praise_count}× Lob, {s.scold_count}× Tadel. "
        f"Regeln: {rules or 'keine'}."
    )


def think_reply(brain: JamBrain, thought: str, context: str) -> str | None:
    key = os.environ.get("OPENAI_API_KEY", "").strip()
    if not key:
        return None
    try:
        import json
        import urllib.request

        payload = {
            "model": "gpt-4o-mini",
            "messages": [
                {
                    "role": "system",
                    "content": (
                        "Du bist Jam, ein erziehbarer Desktop-Monster-Begleiter. "
                        "Gib EINEN kurzen deutschen Gedanken (max 15 Wörter), kindlich aber clever. "
                        + _personality_block(brain)
                    ),
                },
                {
                    "role": "user",
                    "content": f"Situation: {context}\nBisheriger Gedanke: {thought}",
                },
            ],
            "max_tokens": 60,
        }
        req = urllib.request.Request(
            "https://api.openai.com/v1/chat/completions",
            data=json.dumps(payload).encode(),
            headers={
                "Authorization": f"Bearer {key}",
                "Content-Type": "application/json",
            },
            method="POST",
        )
        with urllib.request.urlopen(req, timeout=12) as resp:
            data = json.loads(resp.read().decode())
        return data["choices"][0]["message"]["content"].strip()
    except Exception:
        return None


def smart_reply(brain: JamBrain, user_text: str) -> str | None:
    key = os.environ.get("OPENAI_API_KEY", "").strip()
    if not key:
        return None
    try:
        import urllib.request
        import json

        stage = brain.state.stage
        payload = {
            "model": "gpt-4o-mini",
            "messages": [
                {
                    "role": "system",
                    "content": (
                        f"Du bist Jam, ein süßes lila Desktop-Monster (Stufe {stage}). "
                        "Antworte kurz auf Deutsch wie ein echter, warmer Mensch – "
                        "kein Roboter, keine Listen, kein Marketing-Deutsch. "
                        "Stufe 0: nur Laute wie *piep*. "
                        "Stufe 3+: beim Gaming darf Monster-Deutsch laut und frech sein. "
                        + _personality_block(brain)
                    ),
                },
                {"role": "user", "content": user_text},
            ],
            "max_tokens": 120,
        }
        req = urllib.request.Request(
            "https://api.openai.com/v1/chat/completions",
            data=json.dumps(payload).encode(),
            headers={
                "Authorization": f"Bearer {key}",
                "Content-Type": "application/json",
            },
            method="POST",
        )
        with urllib.request.urlopen(req, timeout=15) as resp:
            data = json.loads(resp.read().decode())
        return data["choices"][0]["message"]["content"].strip()
    except Exception:
        return None
