"""Coalesced asynchronous shadow refresh after committed match mutations.

No writes to the live match database and no live strategy activation.
"""
from __future__ import annotations
import threading
import time
from datetime import datetime, timezone
from pathlib import Path

class ShadowRefreshScheduler:
    def __init__(self, database, registry, refresh_fn=None, quiet_seconds=0.75):
        self.database=Path(database)
        self.registry=Path(registry)
        self._refresh_fn=refresh_fn
        self.quiet_seconds=quiet_seconds
        self._lock=threading.Lock()
        self._event=threading.Event()
        self._worker=None
        self._requested=0
        self._completed=0
        self._status='idle'
        self._error=None
        self._last_result=None
        self._last_completed_utc=None

    def request(self):
        with self._lock:
            self._requested+=1
            self._status='queued'
            if self._worker is None or not self._worker.is_alive():
                self._worker=threading.Thread(target=self._run,daemon=True,name='v2-shadow-refresh')
                self._worker.start()
            self._event.set()
            return self._requested

    def snapshot(self):
        with self._lock:
            return {'mode':'shadow-only','status':self._status,'requested':self._requested,
                    'completed':self._completed,'last_error':self._error,
                    'last_completed_utc':self._last_completed_utc,
                    'last_result':self._last_result,'live_activation':False}

    def _run(self):
        while True:
            self._event.wait()
            self._event.clear()
            time.sleep(self.quiet_seconds)
            with self._lock:
                target=self._requested
                self._status='running'
            try:
                fn=self._refresh_fn
                if fn is None:
                    from qualification_refresh_v2 import refresh
                    fn=refresh
                result=fn(self.database,self.registry)
                error=None
            except Exception as exc:
                result=None
                error=f'{type(exc).__name__}: {exc}'[:500]
            with self._lock:
                self._completed=target
                self._last_result=result
                self._error=error
                self._last_completed_utc=datetime.now(timezone.utc).isoformat()
                if self._requested!=target:
                    self._status='queued'
                    self._event.set()
                else:
                    self._status='error' if error else 'complete'
                    # Retire under lock; a new request will create a fresh worker.
                    self._worker=None
                    return
