import requests
import config
from db import get_db
from services.filters import now_iso


def refresh_flows():
    """Core refresh logic. Raises on failure so callers (the manual API
    route) can report a meaningful error back to the client."""
    if not config.WEBHOOK_FLOWS_URL:
        raise RuntimeError('WEBHOOK_FLOWS_URL is not configured')

    resp = requests.get(config.WEBHOOK_FLOWS_URL, timeout=15)
    resp.raise_for_status()
    data = resp.json()

    payload = data[0] if isinstance(data, list) else data
    if not payload or not isinstance(payload.get('workflows'), list):
        raise RuntimeError('Unexpected response shape from flows webhook')

    conn = get_db()
    try:
        for wf in payload['workflows']:
            wf_id = wf.get('id')
            wf_name = wf.get('name')
            active = wf.get('active')  # real n8n activation state, if reported
            if not wf_id:
                continue

            row = conn.execute('SELECT id FROM Flow WHERE id = ?', (wf_id,)).fetchone()
            if row:
                if isinstance(active, bool):
                    conn.execute(
                        'UPDATE Flow SET name = ?, isActive = ?, updatedAt = ? WHERE id = ?',
                        (wf_name, 1 if active else 0, now_iso(), wf_id),
                    )
                else:
                    conn.execute(
                        'UPDATE Flow SET name = ?, updatedAt = ? WHERE id = ?',
                        (wf_name, now_iso(), wf_id),
                    )
            else:
                conn.execute(
                    'INSERT INTO Flow (id, name, isActive, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?)',
                    (wf_id, wf_name, 1 if active is not False else 0, now_iso(), now_iso()),
                )
        conn.commit()
        return {'synced': len(payload['workflows'])}
    finally:
        conn.close()


def refresh_flows_job():
    try:
        result = refresh_flows()
        print(f"[refresh_flows_job] Synced {result['synced']} flow(s) at {now_iso()}")
    except Exception as err:
        print(f'[refresh_flows_job] Failed to refresh flows webhook: {err}')
