//! Synor Hosting Gateway Binary
//!
//! Runs the hosting gateway that serves content from Synor Storage
//! based on subdomain and custom domain routing.
//!
//! Usage:
//!   hosting-gateway --domain synor.cc --storage-url http://localhost:8180
//!   hosting-gateway --config /path/to/config.toml

use synor_hosting::{HostingGateway, GatewayConfig};
use std::net::SocketAddr;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Initialize logging
    let log_level = std::env::var("RUST_LOG").unwrap_or_else(|_| "info".to_string());
    eprintln!("Starting Synor Hosting Gateway (log level: {})", log_level);

    // Parse command line arguments
    let args: Vec<String> = std::env::args().collect();

    let listen_addr: SocketAddr = args.iter()
        .position(|a| a == "--listen" || a == "-l")
        .and_then(|i| args.get(i + 1))
        .and_then(|s| s.parse().ok())
        .or_else(|| std::env::var("LISTEN_ADDR").ok()?.parse().ok())
        .unwrap_or_else(|| "0.0.0.0:8080".parse().unwrap());

    let hosting_domain = args.iter()
        .position(|a| a == "--domain" || a == "-d")
        .and_then(|i| args.get(i + 1))
        .cloned()
        .or_else(|| std::env::var("HOSTING_DOMAIN").ok())
        .unwrap_or_else(|| "synor.cc".to_string());

    let storage_url = args.iter()
        .position(|a| a == "--storage-url" || a == "-s")
        .and_then(|i| args.get(i + 1))
        .cloned()
        .or_else(|| std::env::var("STORAGE_GATEWAY_URL").ok())
        .unwrap_or_else(|| "http://localhost:8180".to_string());

    let rate_limit: u32 = args.iter()
        .position(|a| a == "--rate-limit")
        .and_then(|i| args.get(i + 1))
        .and_then(|s| s.parse().ok())
        .or_else(|| std::env::var("RATE_LIMIT").ok()?.parse().ok())
        .unwrap_or(100);

    let enable_logging = !args.contains(&"--quiet".to_string());

    // Build configuration
    let config = GatewayConfig {
        listen_addr,
        hosting_domain: hosting_domain.clone(),
        storage_gateway_url: storage_url.clone(),
        https_enabled: false, // TODO: Add HTTPS support via CLI
        ssl_cert_path: None,
        ssl_key_path: None,
        rate_limit,
        max_body_size: 10 * 1024 * 1024,
        enable_logging,
        cache_ttl: 3600,
    };

    eprintln!("Configuration:");
    eprintln!("  Listen: {}", config.listen_addr);
    eprintln!("  Domain: {}", config.hosting_domain);
    eprintln!("  Storage: {}", config.storage_gateway_url);
    eprintln!("  Rate limit: {} req/s", config.rate_limit);

    // Create and start the gateway
    let gateway = HostingGateway::new(config);

    eprintln!("\nHosting gateway is running!");
    eprintln!("  Access: http://<name>.{}", hosting_domain);
    eprintln!("  Health: http://{}/health", listen_addr);
    eprintln!("  Info: http://{}/info", listen_addr);
    eprintln!("\nPress Ctrl+C to stop\n");

    gateway.start().await?;

    Ok(())
}
