import requests
import config
from services.filters import now_iso
from services.normalize import persist_runs


def poll_executions_job():
    if not config.WEBHOOK_EXECUTIONS_URL:
        print('[poll_executions_job] WEBHOOK_EXECUTIONS_URL is not set, skipping.')
        return

    try:
        resp = requests.get(config.WEBHOOK_EXECUTIONS_URL, timeout=15)
        resp.raise_for_status()
        data = resp.json()
    except Exception as err:
        print(f'[poll_executions_job] Failed to poll executions webhook: {err}')
        return

    if not isinstance(data, list):
        print(f'[poll_executions_job] Unexpected response shape: {data!r}')
        return

    polled_at = now_iso()
    persist_runs(data, polled_at)
    print(f'[poll_executions_job] Persisted {len(data)} run(s) at {polled_at}')
