"""cortex/circadian/consolidation/_helpers.py — Shared utilities for consolidation."""
from __future__ import annotations

import json
import logging
from datetime import datetime, timezone

logger = logging.getLogger(__name__)

MAX_CLAIMS_PER_BATCH: int = 15


def _parse_dt(dt_str: str) -> datetime:
    """Parse an ISO datetime string to a timezone-aware datetime."""
    dt = datetime.fromisoformat(dt_str)
    if dt.tzinfo is None:
        dt = dt.replace(tzinfo=timezone.utc)
    return dt


def _parse_json_list(text: str) -> list:
    """Safely parse LLM JSON response as a list."""
    text = text.strip()
    try:
        data = json.loads(text)
        if isinstance(data, list):
            return data
        if isinstance(data, dict) and "proposals" in data:
            return data["proposals"]
        return []
    except json.JSONDecodeError:
        logger.warning("[M6b] JSON parse failed (list): %r", text[:200])
        return []


def _parse_json_dict(text: str) -> dict:
    """Safely parse LLM JSON response as a dict."""
    text = text.strip()
    try:
        data = json.loads(text)
        if isinstance(data, dict):
            return data
        return {}
    except json.JSONDecodeError:
        logger.warning("[M6b] JSON parse failed (dict): %r", text[:200])
        return {}
