"""AttitudeManager — load, save, and decay attitude state."""
from __future__ import annotations

import json
import logging

from kokoro_chat.attitude.state import AttitudeState
from kokoro_chat.storage.protocol import AttitudeStore, CacheStore

logger = logging.getLogger(__name__)


class AttitudeManager:
    """Manage attitude state with cache-first reads and write-through saves."""

    def __init__(self, store: AttitudeStore, cache: CacheStore) -> None:
        self._store = store
        self._cache = cache

    async def load(self, char_id: str, user_id: str) -> AttitudeState:
        """Load attitude: cache → store → new. Applies time decay if loaded from store."""
        cached = await self._cache.get_attitude(user_id, char_id)
        if cached:
            att = AttitudeState(char_id, user_id)
            att.affection = cached.get("affection", 50)
            att.trust = cached.get("trust", 50)
            att.mood = cached.get("mood", "neutral")
            try:
                att.attitude_modifiers = json.loads(
                    cached.get("modifiers_json", "[]"),
                )
            except (json.JSONDecodeError, TypeError):
                att.attitude_modifiers = []
            return att

        record = await self._store.get_or_create(user_id, char_id)
        att = AttitudeState(char_id, user_id)
        att.affection = record.affection
        att.trust = record.trust
        att.mood = record.mood
        try:
            att.attitude_modifiers = json.loads(record.modifiers_json or "[]")
        except (json.JSONDecodeError, TypeError):
            att.attitude_modifiers = []

        if att.apply_time_decay():
            modifiers_json = json.dumps(att.attitude_modifiers, ensure_ascii=False)
            await self._store.save(
                user_id, char_id,
                affection=att.affection,
                trust=att.trust,
                mood=att.mood,
                modifiers_json=modifiers_json,
            )

        await self._cache.set_attitude(user_id, char_id, {
            "affection": att.affection,
            "trust": att.trust,
            "mood": att.mood,
            "modifiers_json": json.dumps(att.attitude_modifiers, ensure_ascii=False),
        })
        return att

    async def save(self, attitude: AttitudeState) -> None:
        """Write-through save to store + cache."""
        modifiers_json = json.dumps(attitude.attitude_modifiers, ensure_ascii=False)
        await self._store.save(
            attitude.user_id,
            attitude.character_id,
            affection=attitude.affection,
            trust=attitude.trust,
            mood=attitude.mood,
            modifiers_json=modifiers_json,
        )
        await self._cache.set_attitude(
            attitude.user_id, attitude.character_id,
            {
                "affection": attitude.affection,
                "trust": attitude.trust,
                "mood": attitude.mood,
                "modifiers_json": modifiers_json,
            },
        )
