"""Celery tasks for async policy checks."""

from __future__ import annotations

from datetime import datetime
from typing import Any, Mapping

from hieromem_core.ingestion.celery_app import app
from hieromem_core.policy.evaluator import MemoryPolicyEvaluator
from hieromem_core.policy.parser import load_policy


def _parse_episode_time(value: Any) -> datetime:
    if isinstance(value, datetime):
        return value
    if isinstance(value, str):
        return datetime.fromisoformat(value)
    raise ValueError(f"Unsupported episode timestamp: {value!r}")


@app.task
def evaluate_policy_insert(payload: Mapping[str, Any]) -> dict[str, Any]:
    policy = load_policy(payload["policy"])
    evaluator = MemoryPolicyEvaluator(policy)
    decision = evaluator.evaluate_insert(
        graph=None,
        total_episodes=int(payload.get("total_episodes", 0)),
        namespace=str(payload.get("namespace") or policy.namespace or "default"),
    )
    return {
        "action": decision.action.value if decision.action else None,
        "allowed": decision.is_allowed(),
        "result": decision.result.value if decision.result else None,
        "reason": decision.reason,
        "warnings": decision.warnings,
    }


@app.task
def retention_sweep(payload: Mapping[str, Any]) -> dict[str, Any]:
    policy = load_policy(payload["policy"])
    evaluator = MemoryPolicyEvaluator(policy)
    episodes = []
    for episode in payload.get("episodes", []):
        episodes.append(
            type("PolicyEpisode", (), {
                "id": episode["id"],
                "tocc": _parse_episode_time(episode["tocc"]),
                "trust": float(episode.get("trust", 1.0)),
            })()
        )
    candidates = evaluator.retention_candidates(episodes)
    candidate_ids = [ep.id for ep in candidates]
    return {
        "candidate_ids": candidate_ids,
        "candidate_count": len(candidate_ids),
    }
