# -*- coding: utf-8 -*-
"""CLI for watcher: register a captured Sota config into SQLite."""
from __future__ import annotations

import hashlib
import json
import sys
from pathlib import Path

from nodes_db import init_db, register_capture


def main() -> int:
    if len(sys.argv) < 2:
        print("Usage: register_capture.py <path-to-capture.json>", file=sys.stderr)
        return 2
    path = Path(sys.argv[1])
    if not path.is_file():
        print(f"FAIL: not found {path}", file=sys.stderr)
        return 2
    raw = path.read_bytes()
    sha = hashlib.sha256(raw).hexdigest()
    data = json.loads(raw.decode("utf-8"))
    vless = [o for o in data.get("outbounds", []) if isinstance(o, dict) and o.get("type") == "vless"]
    if not vless:
        print("FAIL: no vless", file=sys.stderr)
        return 2
    server = str(vless[0].get("server") or "?")
    port = int(vless[0].get("server_port") or 0)
    init_db()
    node_id = register_capture(
        file_path=str(path),
        server=server,
        port=port,
        sha256=sha,
        vless_count=len(vless),
        make_active=True,
    )
    print(f"OK id={node_id} server={server}:{port}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
