/// Stream command — compile and stream via bitstream relay.

use std::fs;
use std::path::Path;

use super::build::compile;
use super::dev::inject_hmr;

pub fn cmd_stream(file: &Path, relay: &str, mode: &str, port: u16) {
    println!("⚡ DreamStack stream");
    println!("   source: {}", file.display());
    println!("   relay:  {}", relay);
    println!("   mode:   {}", mode);
    println!("   port:   {}", port);
    println!();

    let source = match fs::read_to_string(file) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("❌ Could not read {}: {}", file.display(), e);
            std::process::exit(1);
        }
    };

    // Inject stream declaration if not present
    let stream_source = if source.contains("stream ") {
        source
    } else {
        // Auto-inject a stream declaration for the first view
        let view_name = {
            let mut lexer = ds_parser::Lexer::new(&source);
            let tokens = lexer.tokenize();
            let mut parser = ds_parser::Parser::new(tokens);
            if let Ok(program) = parser.parse_program() {
                program.declarations.iter()
                    .find_map(|d| if let ds_parser::ast::Declaration::View(v) = d { Some(v.name.clone()) } else { None })
                    .unwrap_or_else(|| "main".to_string())
            } else {
                "main".to_string()
            }
        };
        format!(
            "{}\nstream {} on \"{}\" {{ mode: {} }}",
            source, view_name, relay, mode
        )
    };

    match compile(&stream_source, file.parent().unwrap_or(Path::new(".")), false) {
        Ok(html) => {
            let html_with_hmr = inject_hmr(&html);
            println!("✅ Compiled with streaming enabled");
            println!("   Open: http://localhost:{port}");
            println!("   Relay: {relay}");
            println!();
            println!("   Make sure the relay is running:");
            println!("   cargo run -p ds-stream");
            println!();

            // Serve the compiled page
            let server = tiny_http::Server::http(format!("0.0.0.0:{port}")).unwrap();
            for request in server.incoming_requests() {
                let response = tiny_http::Response::from_string(&html_with_hmr)
                    .with_header(
                        tiny_http::Header::from_bytes(
                            &b"Content-Type"[..],
                            &b"text/html; charset=utf-8"[..],
                        ).unwrap(),
                    );
                let _ = request.respond(response);
            }
        }
        Err(e) => {
            eprintln!("❌ Compile error: {e}");
            std::process::exit(1);
        }
    }
}
