"""Backfill one-shot: empurra todos os crashes do SQLite local pro IronDome Cloud.

Uso:
  IRONDOME_API_KEY=idk_... IRONDOME_CLOUD_URL=http://127.0.0.1:13010 \
      python3 backfill_to_cloud.py

Use SSH tunnel se DNS ainda não propagou:
  ssh -L 13010:127.0.0.1:3010 hostinger -N
"""
import json
import os
import sqlite3
import sys
import time
import urllib.error
import urllib.request

URL = os.environ.get('IRONDOME_CLOUD_URL', '').rstrip('/')
KEY = os.environ.get('IRONDOME_API_KEY', '')
DB = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data', 'aviator.db')
BATCH = 500

if not URL or not KEY:
    print('Missing IRONDOME_CLOUD_URL or IRONDOME_API_KEY')
    sys.exit(1)


def post(path, body):
    req = urllib.request.Request(
        f'{URL}{path}', data=json.dumps(body).encode('utf-8'),
        headers={'Content-Type': 'application/json', 'x-api-key': KEY}, method='POST',
    )
    with urllib.request.urlopen(req, timeout=30) as r:
        return json.loads(r.read().decode('utf-8'))


def main():
    conn = sqlite3.connect(DB)
    rows = conn.execute('SELECT ts, value FROM crashes ORDER BY id ASC').fetchall()
    total = len(rows)
    print(f'local crashes: {total}')
    sent = 0
    t0 = time.time()
    for i in range(0, total, BATCH):
        chunk = [{'ts': float(r[0]), 'value': float(r[1])} for r in rows[i:i+BATCH]]
        try:
            r = post('/api/v1/crashes/bulk', chunk)
            sent += r.get('inserted', 0)
            print(f'  batch {i//BATCH+1}: +{len(chunk)} (total sent: {sent})')
        except urllib.error.HTTPError as e:
            print(f'  batch {i//BATCH+1} FAIL: {e} {e.read()}')
            sys.exit(2)
        except Exception as e:
            print(f'  batch {i//BATCH+1} FAIL: {e}')
            sys.exit(2)
    print(f'done in {time.time()-t0:.1f}s — {sent}/{total} ingested')


if __name__ == '__main__':
    main()
