// src/modules/ink.rs

use crate::parser::interpreter::Interpreter;
use crate::parser::types::{
    Value,
    FunctionValue,
    InkIteratorHandle,
    InkIteratorState,
    InkIteratorKind,
};
use std::sync::{Arc, Mutex};

fn ink_bridge_fn(_interp: &mut Interpreter, args: Vec<Value>) -> Result<Value, String> {
    if args.len() != 2 {
        return Err(format!("ink => expected 2 integer args, got {}", args.len()));
    }
    let start_i = match &args[0] {
        Value::Int(n) => *n,
        other => return Err(format!("ink => first arg must be int, got {:?}", other)),
    };
    let end_i = match &args[1] {
        Value::Int(n) => *n,
        other => return Err(format!("ink => second arg must be int, got {:?}", other)),
    };

    let handle = InkIteratorHandle {
        kind: InkIteratorKind::Core(Arc::new(Mutex::new(InkIteratorState {
            current: start_i,
            end: end_i,
            done: false,
        }))),
    };
    Ok(Value::InkIterator(handle))
}

/// Call this during your interpreter initialization to make `ink(...)` available.
pub fn register_ink(interp: &mut Interpreter) {
    let f = Arc::new(Mutex::new(ink_bridge_fn));
    interp.register_dynamic_function("ink", f);
    interp.set_variable(
        "ink",
        Value::Function(Box::new(FunctionValue::Named("ink".to_string())))
    );
}
