#![allow(dead_code)]

use anyhow::Result;
use tsnative::codegen::CodeGen;
use tsnative::swc_transform;

fn main() -> Result<()> {
    let args: Vec<String> = std::env::args().collect();
    
    if args.len() < 2 {
        eprintln!("Usage: ts-native <input.ts> [-o output.obj]");
        std::process::exit(1);
    }
    
    // Parse arguments: ts-native <input.ts> [-o <output>]
    let mut input_file = String::new();
    let mut output_file = String::new();
    {
        let mut i = 1;
        while i < args.len() {
            match args[i].as_str() {
                "-o" | "--output" => {
                    i += 1;
                    if i < args.len() {
                        output_file = args[i].clone();
                    }
                }
                arg if !arg.starts_with('-') && input_file.is_empty() => {
                    input_file = arg.to_string();
                }
                _ => {}
            }
            i += 1;
        }
    }

    if input_file.is_empty() {
        eprintln!("Error: no input file specified");
        std::process::exit(1);
    }

    if output_file.is_empty() {
        let input_path_buf = std::path::PathBuf::from(&input_file);
        let stem = input_path_buf
            .file_stem()
            .unwrap_or(std::ffi::OsStr::new("a"))
            .to_string_lossy()
            .to_string();
        let dir = input_path_buf
            .parent()
            .unwrap_or(std::path::Path::new("."));
        output_file = dir.join(format!("{}.obj", stem)).to_string_lossy().to_string();
    }

    let _input_path = std::path::PathBuf::from(&input_file);

    let source = std::fs::read_to_string(&input_file)?;
    
    println!("\n解析 TypeScript: {}", input_file);
    let mut hir = swc_transform::parse(&source)?;
    
    println!("生成 native 代码...");
    let mut codegen = CodeGen::new();
    let binary = codegen.compile_coff(&mut hir)?;
    
    let obj_file = if output_file.ends_with(".obj") {
        output_file.clone()
    } else {
        format!("{}.obj", output_file)
    };
    
    std::fs::write(&obj_file, &binary)?;
    println!("COFF: {} ({} bytes)", obj_file, binary.len());
    println!("Run: tsn-loader {}", input_file);
    
    Ok(())
}
