#!/usr/bin/env python3
"""Recover or expose stale outbox processing rows.

Usage examples:
  OUTBOX_STALE_RECOVERY_MODE=manual_only python scripts/recover_stale_outbox.py
  OUTBOX_STALE_RECOVERY_MODE=retry_pending python scripts/recover_stale_outbox.py
"""
from __future__ import annotations

import os
import sys
from pathlib import Path

PROJECT_ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(PROJECT_ROOT))
os.chdir(PROJECT_ROOT)

from app.integration_outbox_service import recover_stale_processing_outbox, outbox_stale_minutes


def main() -> int:
    mode = os.getenv("OUTBOX_STALE_RECOVERY_MODE", "manual_only")
    actor = os.getenv("OUTBOX_WORKER_ID", f"recover_stale_outbox:{os.getpid()}")
    limit = int(os.getenv("OUTBOX_STALE_RECOVERY_LIMIT", "100"))
    stale_minutes = outbox_stale_minutes()
    recovered = recover_stale_processing_outbox(
        mode=mode,
        actor=actor,
        limit=limit,
        stale_minutes=stale_minutes,
    )
    print(f"Mode: {mode}")
    print(f"Stale threshold minutes: {stale_minutes}")
    print(f"Recovered/exposed stale items: {len(recovered)}")
    for item in recovered:
        print(f"- {item.get('id')} {item.get('target_system')}.{item.get('action_type')} -> {item.get('status')}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
