"""Start the relay server.

    python relay.py                          # uses configs/relay.toml if present
    python relay.py --port 8888 --token SECRET
    python relay.py --generate-token         # print a random token and exit

Command-line options override values from the config file.
"""

from __future__ import annotations

import argparse
import os
import secrets
import sys
from dataclasses import replace
from pathlib import Path

from app import __version__
from app.config import (
    ENV_RELAY_TOKEN,
    ConfigError,
    LoggingConfig,
    RelayConfig,
    load_config,
)
from app.logging_setup import configure_logging
from main import run_relay

DEFAULT_CONFIG = Path(__file__).resolve().parent / "configs" / "relay.toml"


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description="Auto Transfer relay server")
    parser.add_argument("--config", help="TOML config file (default: configs/relay.toml if it exists)")
    parser.add_argument("--host", help="interface to listen on (default 0.0.0.0)")
    parser.add_argument("--port", type=int, help="port to listen on")
    parser.add_argument("--token", help=f"access token clients must send (or set ${ENV_RELAY_TOKEN})")
    parser.add_argument("--data-dir", help="where encrypted chunks and the database are stored")
    parser.add_argument("--cert", help="TLS certificate (PEM) to serve HTTPS")
    parser.add_argument("--key", help="TLS private key (PEM)")
    parser.add_argument("--generate-token", action="store_true", help="print a random token and exit")
    parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
    args = parser.parse_args(argv)

    if args.generate_token:
        print(secrets.token_urlsafe(32))
        return 0

    config_path = args.config or (str(DEFAULT_CONFIG) if DEFAULT_CONFIG.exists() else None)
    try:
        if config_path:
            loaded = load_config(config_path, "relay")
            settings, logging_config = loaded.settings, loaded.logging
        else:
            settings = RelayConfig(auth_token=os.environ.get(ENV_RELAY_TOKEN, ""))
            logging_config = LoggingConfig()
    except ConfigError as exc:
        print(f"Configuration error: {exc}", file=sys.stderr)
        return 2

    overrides = {
        "host": args.host,
        "port": args.port,
        "auth_token": args.token,
        "data_dir": args.data_dir,
        "ssl_cert_path": args.cert,
        "ssl_key_path": args.key,
    }
    settings = replace(settings, **{k: v for k, v in overrides.items() if v is not None})
    errors = settings.validate()
    if errors:
        print("Configuration error: " + "; ".join(errors), file=sys.stderr)
        return 2

    configure_logging("relay", logging_config)
    if config_path:
        print(f"Using config {config_path}", file=sys.stderr)
    return run_relay(settings)


if __name__ == "__main__":
    sys.exit(main())
