#!/usr/bin/env python3
"""Register an internally hosted SGB domain feed with Technitium DNS Server.

The script does not upload thousands of domains one by one. Instead, it adds a
single managed URL to Technitium's existing block-list sources and asks the
server to refresh. Existing sources are retained. A bearer token with Settings:
View and Settings:Modify permissions is required; no password is stored here.
"""

from __future__ import annotations

import argparse
import json
import os
import sys
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode
from urllib.request import Request, urlopen


def api_call(base_url: str, path: str, token: str, data: dict[str, str] | None = None) -> dict:
    payload = urlencode(data).encode() if data is not None else None
    request = Request(
        f"{base_url.rstrip('/')}{path}",
        data=payload,
        headers={
            "Accept": "application/json",
            "Authorization": f"Bearer {token}",
            **({"Content-Type": "application/x-www-form-urlencoded"} if payload else {}),
        },
        method="POST" if payload is not None else "GET",
    )
    try:
        with urlopen(request, timeout=30) as response:
            result = json.load(response)
    except (HTTPError, URLError, TimeoutError, json.JSONDecodeError) as exc:
        raise RuntimeError(f"Technitium API request failed: {exc}") from exc
    if result.get("status") != "ok":
        raise RuntimeError(f"Technitium API returned an error: {result}")
    return result


def extract_urls(settings: dict) -> list[str]:
    value = settings.get("blockListUrls", [])
    if isinstance(value, str):
        return [item.strip() for item in value.split(",") if item.strip() and item.strip().lower() != "false"]
    if isinstance(value, list):
        return [str(item).strip() for item in value if str(item).strip()]
    raise RuntimeError("Unexpected blockListUrls format returned by Technitium.")


def main() -> int:
    parser = argparse.ArgumentParser(description="Add an SGB feed URL to existing Technitium block-list sources.")
    parser.add_argument("--server", default=os.environ.get("TECHNITIUM_URL"), help="Technitium base URL, e.g. https://127.0.0.1:53443")
    parser.add_argument("--token", default=os.environ.get("TECHNITIUM_TOKEN"), help="Bearer token; prefer TECHNITIUM_TOKEN environment variable.")
    parser.add_argument("--feed-url", required=True, help="HTTPS URL of the generated sgb-domains.txt file.")
    parser.add_argument("--update-hours", type=int, default=24, choices=range(1, 169), metavar="1-168", help="Technitium refresh interval (default: 24).")
    parser.add_argument("--apply", action="store_true", help="Apply the change. Without this flag, the script is read-only.")
    args = parser.parse_args()
    if not args.server or not args.token:
        parser.error("--server and --token are required (or set TECHNITIUM_URL and TECHNITIUM_TOKEN).")
    if not args.feed_url.startswith("https://"):
        parser.error("--feed-url must use HTTPS to protect threat-intelligence integrity in transit.")

    response = api_call(args.server, "/api/settings/get", args.token)
    settings = response.get("response", {})
    current_urls = extract_urls(settings)
    feed_url = args.feed_url.rstrip("/")
    already_present = feed_url in current_urls
    desired_urls = current_urls if already_present else [*current_urls, feed_url]

    print("Current block-list sources:")
    for url in current_urls:
        print(f"  - {url}")
    print(f"\nSGB feed: {feed_url} ({'already present' if already_present else 'will be added'})")
    print(f"Refresh interval: {args.update_hours} hour(s)")
    if not args.apply:
        print("\nDry run only. Re-run with --apply to update Technitium.")
        return 0

    api_call(
        args.server,
        "/api/settings/set",
        args.token,
        {"blockListUrls": ",".join(desired_urls), "blockListUpdateIntervalHours": str(args.update_hours)},
    )
    api_call(args.server, "/api/settings/forceUpdateBlockLists", args.token, {})
    print("SGB feed registered and a block-list refresh was requested.")
    return 0


if __name__ == "__main__":
    try:
        raise SystemExit(main())
    except RuntimeError as exc:
        print(f"ERROR: {exc}", file=sys.stderr)
        raise SystemExit(1)
