#!/usr/bin/env python3
"""Seed uptime-kuma monitors via the API after the ECS service is up.

Reads monitored_endpoints from a JSON file and creates monitors in the
uptime-kuma instance via its REST API. Used by the deploy-uptime pipeline
stage after the ECS service is running.

Usage:
    seed_uptime_monitors.py <endpoints.json> <uptime_url> [--token <token>]

The endpoints.json file is an array of:
    {"name": "...", "url": "...", "type": "http|dns|tcp",
     "interval_seconds": 60, "timeout_seconds": 30}
"""

import argparse
import json
import os
import sys
import urllib.request
import urllib.error


def create_monitor(uptime_url, endpoint, token=None):
    """Create a single monitor in uptime-kuma via the API."""
    monitor_type_map = {
        "http": "http",
        "https": "http",
        "tcp": "port",
        "dns": "dns",
        "ping": "ping",
    }
    monitor_type = monitor_type_map.get(endpoint.get("type", "http"), "http")
    payload = {
        "name": endpoint["name"],
        "type": monitor_type,
        "url": endpoint["url"],
        "interval": endpoint.get("interval_seconds", 60),
        "timeout": endpoint.get("timeout_seconds", 30),
    }
    url = f"{uptime_url}/api/monitor"
    data = json.dumps(payload).encode()
    req = urllib.request.Request(url, data=data, method="POST")
    req.add_header("Content-Type", "application/json")
    if token:
        req.add_header("Authorization", f"Bearer {token}")
    try:
        with urllib.request.urlopen(req, timeout=10) as resp:
            result = json.loads(resp.read())
            return {"status": "created", "monitor": endpoint["name"], "result": result}
    except urllib.error.HTTPError as e:
        return {"status": "error", "monitor": endpoint["name"], "error": str(e)}
    except Exception as e:
        return {"status": "error", "monitor": endpoint["name"], "error": str(e)}


def seed_monitors(endpoints, uptime_url, token=None):
    """Seed all monitors from the endpoints list."""
    results = []
    for endpoint in endpoints:
        result = create_monitor(uptime_url, endpoint, token)
        results.append(result)
    return results


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Seed uptime-kuma monitors")
    parser.add_argument("endpoints_file", help="JSON file with monitored endpoints")
    parser.add_argument("uptime_url", help="URL of the uptime-kuma instance")
    parser.add_argument("--token", default=None, help="Auth token (if required)")
    args = parser.parse_args()

    with open(args.endpoints_file) as f:
        endpoints = json.load(f)

    results = seed_monitors(endpoints, args.uptime_url, args.token)
    for r in results:
        print(f"  [{r['status']}] {r['monitor']}")
    created = sum(1 for r in results if r["status"] == "created")
    print(f"Seeded {created}/{len(results)} monitors")