use std::fs;

use crate::interpreter::InterpreterState;
use crate::lexer::{LexerInfo, lexical_analysis, LexResult};

/// Execute the contents of a script file.
pub fn exec_file(interpreter: &mut InterpreterState, filename: &str) -> bool {
    // Read the whole file
    let source = match fs::read_to_string(filename) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("Cannot read file: {} ({})", filename, e);
            return false;
        }
    };

    let mut lexer_info = LexerInfo::new(filename, source.clone());

    let result = lexical_analysis(&mut lexer_info);

    match result {
        LexResult::Ok(tokens) => {
            for token in tokens {
                if !interpreter.execute(&token) {
                    return false;
                }
            }
            true
        }

        LexResult::Err(err) => {
            dbg!(err);
            false
        }
    }
}

/// Stand-alone file execution entry point.
pub fn run_file(filename: &str) -> i32 {
    println!("Executing file: {}", filename);

    let mut interpreter = InterpreterState::new();
    if !interpreter.init() {
        return 1;
    }

    if exec_file(&mut interpreter, filename) {
        0
    } else {
        1
    }
}
