#!/usr/bin/env python3
"""Aria DLQ-Retry Cron-Service (KAR-233 Phase 2).

Pollt /root/aria/state/audit.sqlite -> dlq Tabelle nach ready-Entries
(ts_next_retry <= now, status='pending'). Aria entscheidet pro Entry
ob Retry sinnvoll. Default: log + mark_retry (kein automatischer Replay).

Spaeter: pro action ein dispatcher der das original-Skript erneut
aufrufen kann.
"""
from __future__ import annotations
import sys as _sys
_sys.path.insert(0, "/root/aria/lib")
from aria_logging import get_logger as _get_logger
_log = _get_logger("aria-dlq-retry")
from aria_audit import dlq_pop_ready, dlq_mark_retry, audit

import json


def main() -> int:
    ready = dlq_pop_ready(limit=20)
    _log.event("dlq_retry_start", n_ready=len(ready))
    if not ready:
        print(f"[dlq-retry] no entries ready", flush=True)
        return 0

    processed = 0
    for entry in ready:
        eid = entry["id"]
        actor = entry["actor"]
        action = entry["action"]
        retry_count = entry["retry_count"]
        max_retries = entry["max_retries"]

        # Heuristik: aktuell kein automatischer Replay — wir markieren als attempted
        # und lassen Aria entscheiden welche Items wirklich retryed werden sollen.
        # Stattdessen logging + audit + reschedule.
        _log.event(
            "dlq_retry_attempt",
            dlq_id=eid,
            actor=actor,
            action=action,
            retry_count=retry_count,
            max_retries=max_retries,
        )
        audit(
            "aria-dlq-retry",
            "retry_attempt",
            target_kind="dlq",
            target_id=str(eid),
            payload={"actor": actor, "action": action, "retry_count": retry_count},
            status="info",
        )
        # Default: mark as failure (no auto-replay), retry-count goes up
        # If retry_count >= max → status=failed automatically by dlq_mark_retry
        dlq_mark_retry(eid, success=False, error="no_auto_replay_dispatcher")
        processed += 1

    _log.event("dlq_retry_done", processed=processed)
    print(f"[dlq-retry] processed={processed} (no auto-replay yet)", flush=True)
    return 0


if __name__ == "__main__":
    _log.event("script_start")
    import sys
    sys.exit(main())
