"""
Feedback Aggregator — Shared utilities.

Common helpers for timestamp formatting, safe division, and record filtering.
"""

import time
import datetime
from typing import List, Any


def to_iso(ts: float) -> str:
    """Convert Unix timestamp to ISO-8601 string."""
    if not ts:
        return ""
    return datetime.datetime.utcfromtimestamp(ts).strftime("%Y-%m-%dT%H:%M:%SZ")


def safe_div(numerator: float, denominator: float,
              default: float = 0.0) -> float:
    """Division that returns default on zero denominator."""
    return round(numerator / denominator, 4) if denominator else default


def filter_records(records: List[Any], **kwargs) -> List[Any]:
    """
    Filter a list of records by field equality.

    filter_records(events, recalled=True, task_id="t1")
    """
    result = []
    for r in records:
        match = True
        for k, v in kwargs.items():
            if getattr(r, k, None) != v:
                match = False
                break
        if match:
            result.append(r)
    return result


def unique_by(records: List[Any], key: str) -> List[Any]:
    """Return records deduplicated by field value (keeps first occurrence)."""
    seen = set()
    out = []
    for r in records:
        val = getattr(r, key, None)
        if val not in seen:
            seen.add(val)
            out.append(r)
    return out


def avg(values: List[float]) -> float:
    """Average of a list; 0.0 if empty."""
    return round(sum(values) / len(values), 4) if values else 0.0


def clamp(v: float, lo: float = 0.0, hi: float = 1.0) -> float:
    return max(lo, min(hi, v))
