#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Confidence decay validator — extracted from brain_validators.py for Law 7 SoC."""
from datetime import datetime, timezone
from pulse.core.brain_utils import (
    load_config, load_json, save_json,
    compute_confidence_decay, EVIDENCE_DIR,
)


def validate_decay(apply: bool = False) -> list:
    """Check and optionally apply confidence decay to evidence."""
    config = load_config()
    decay_rate = config.get("decay", {}).get("confidence_decay_rate", 0.005)
    max_age = config.get("validation", {}).get("max_evidence_age_days", 365)
    now = datetime.now(timezone.utc)
    decayed = []

    if not EVIDENCE_DIR.exists():
        return decayed

    for ef in sorted(EVIDENCE_DIR.rglob("*.json")):
        items = load_json(ef)
        if not isinstance(items, list):
            continue
        modified = False
        for item in items:
            ts = item.get("date") or item.get("timestamp")
            if not ts:
                continue
            try:
                ts_str = str(ts).replace("Z", "+00:00")
                if "T" in ts_str:
                    d = datetime.fromisoformat(ts_str)
                else:
                    d = datetime.fromisoformat(ts_str).replace(tzinfo=timezone.utc)
                days_old = (now - d).days
            except (ValueError, TypeError):
                continue

            if days_old <= 0:
                continue

            original = item.get("confidence", 0.8)
            new_conf = compute_confidence_decay(original, days_old, decay_rate)

            if new_conf != original:
                decayed.append({
                    "file": ef.name,
                    "days_old": days_old,
                    "original": original,
                    "decayed": new_conf,
                    "stale": days_old > max_age,
                })
                if apply:
                    item["confidence"] = new_conf
                    item["decay_applied"] = now.isoformat()
                    modified = True

        if modified and apply:
            save_json(ef, items)
    return decayed
