// Copyright 2026 Jordan Castro <jordan@grupojvm.com>
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
//
// cargo test --test test_all --no-default-features --features "lua,python,js,testing" -- --nocapture --test-threads=1

#[cfg(test)]
mod tests {
    use std::{
        ffi::{CStr, c_char, c_void},
    };

    use pixelscript::{
        lua::LuaScripting, python::PythonScripting, shared::{
            PixelScript,
            var::{pxs_Var, pxs_VarT},
            utils::{execute_code}
        }, *
    };
    use etffi::{cstring::CStringSafe, borrow_string, create_raw_string, free_raw_string, own_string, ptr_magic::PtrMagic};

    #[derive(Clone)]
    struct DiaryItem {
        text: String
    }

    impl PtrMagic for DiaryItem {}

    extern "C" fn free_diary_item(ptr: *mut c_void) {
        println!("DIARY ITEM FREED");
        let _ = DiaryItem::from_raw(ptr as *mut DiaryItem);
    }

    extern "C" fn new_diary_item(args: *mut pxs_Var) -> pxs_VarT {
        let item = pxs_listget(args, 1);
        let item_str = pxs_getstring(item);
        let item_string = borrow_string!(item_str).to_string();
        let diary_item = DiaryItem{text: item_string};
        let type_name = create_raw_string!("DiaryItem");
        let obj = pxs_newobject(
            diary_item.into_raw() as *mut c_void, 
            free_diary_item, 
            type_name
        );
        unsafe {
            free_raw_string!(type_name);
        }
        pxs_newhost(obj)
    }

    struct Diary {
        #[allow(unused)]
        owner: DiaryOwner,
        items: Vec<DiaryItem>,
    }

    impl Diary {
        pub fn new(owner: DiaryOwner, items: Vec<DiaryItem>) -> Self {
            Diary {
                owner,
                items,
            }
        }
    }
    impl PtrMagic for Diary {}

    pub extern "C" fn free_diary(ptr: *mut c_void) {
        println!("DIARY FREED");
        let _ = Diary::from_raw(ptr as *mut Diary);
    }

    extern "C" fn add_item(args: pxs_VarT) -> pxs_VarT {
        // Deref
        unsafe {
            let vars = pxs_Var::from_borrow(args);
            println!("args: {:#?}", vars);
            let pixel_object_var = pxs_listget(args, 1);
            let host_ptr = pxs_gethost(pxs_listget(args, 0), pixel_object_var);
            let d = Diary::from_borrow(host_ptr as *mut Diary);

            let item = pxs_listget(args, 2);
            let contents = pxs_getstring(item);

            let str = own_string!(contents);

            d.items.push(DiaryItem { text: str });

            pxs_newnull()
        }
    }

    extern "C" fn new_diary(args: pxs_VarT) -> pxs_VarT {
        unsafe {
            let len = pxs_listlen(args);
            let owner_arg = pxs_listget(args, 1);
            let host_ptr = pxs_gethost(pxs_listget(args,0), owner_arg);
            let item_list = pxs_listget(args, 1);
            let mut items = vec![];
            for i in 0..pxs_listlen(item_list) {
                let var = pxs_listget(item_list, i);
                let dstr = pxs_debugvar(var);
                println!("{}", borrow_string!(dstr));
                let ptr = pxs_gethost(pxs_listget(args, 0), var);
                free_raw_string!(dstr);
                let item = DiaryItem::from_borrow(ptr as *mut DiaryItem);
                items.push(item.clone());
            }
            // let name_arg = pxs_Var::from_borrow(pxs_listget(args, 1));
            let p_name = DiaryOwner::from_borrow(host_ptr as *mut DiaryOwner);
            let p = Diary::new(p_name.clone(), items);
            let typename = create_raw_string!("Diary");

            let ptr = Diary::into_raw(p) as *mut c_void;
            let pixel_object = pxs_newobject(ptr, free_diary, typename);
            let add_item_raw = create_raw_string!("add_item");

            pxs_object_add_reffunc(pixel_object, add_item_raw, add_item);
            // Save...
            let var = pxs_newhost(pixel_object);

            free_raw_string!(add_item_raw);
            free_raw_string!(typename);
            var
        }
    }

    #[allow(unused)]
    #[derive(Clone)]
    struct DiaryOwner {
        pub name: String
    }

    impl PtrMagic for DiaryOwner {}

    extern "C" fn free_diary_owner(ptr: *mut c_void) {
        println!("DIARY OWNER FREED");
        let _ = DiaryOwner::from_raw(ptr as *mut DiaryOwner);
    }

    extern "C" fn new_diary_owner(args: pxs_VarT) -> pxs_VarT {
        unsafe {
            let p_name = pxs_Var::from_borrow(pxs_listget(args, 1));
            let p_name = p_name.get_string().unwrap();
            let p = DiaryOwner{name: p_name.clone()};
            let typename = create_raw_string!("DiaryOwner");

            let ptr = DiaryOwner::into_raw(p) as *mut c_void;
            let pixel_object = pxs_newobject(ptr, free_diary_owner, typename);
            let var = pxs_newhost(pixel_object);

            free_raw_string!(typename);
            var
        }
    }

    struct Person {
        name: String,
    }

    impl Person {
        pub fn new(n_name: String) -> Self {
            Person { name: n_name }
        }

        pub fn set_name(&mut self, n_name: String) {
            self.name = n_name;
        }

        pub fn get_name(&self) -> String {
            self.name.clone()
        }
    }

    impl PtrMagic for Person {}

    pub extern "C" fn free_person(ptr: *mut c_void) {
        println!("PERSON FREED");
        let _ = Person::from_raw(ptr as *mut Person);
    }

    pub extern "C" fn set_name(args: *mut pxs_Var) -> *mut pxs_Var {
        unsafe {
            // Get ptr
            let pixel_object_var = pxs_listget(args, 1);
            let host_ptr = pxs_gethost(pxs_listget(args, 0), pixel_object_var);
            let p = Person::from_borrow(host_ptr as *mut Person);

            // Check if first arg is self or nme
            let name = {
                let first_arg = pxs_Var::from_borrow(pxs_listget(args, 2));
                if first_arg.is_string() {
                    first_arg
                } else {
                    pxs_Var::from_borrow(pxs_listget(args, 3))
                }
            };

            p.set_name(name.get_string().unwrap().clone());

            pxs_Var::into_raw(pxs_Var::new_null())
        }
    }

    pub extern "C" fn get_name(args: *mut pxs_Var) -> *mut pxs_Var {
        unsafe {
            // Get ptr
            let pixel_object_var = pxs_listget(args, 1);
            let host_ptr = pxs_gethost(pxs_listget(args, 0), pixel_object_var);
            let p = Person::from_borrow(host_ptr as *mut Person);

            pxs_Var::new_string(p.get_name().clone()).into_raw()
        }
    }

    pub extern "C" fn new_person(args: *mut pxs_Var) -> *mut pxs_Var {
        unsafe {
            let p_name = pxs_Var::from_borrow(pxs_listget(args, 1));
            let p_name = p_name.get_string().unwrap();
            let p = Person::new(p_name.clone());
            let typename = create_raw_string!("Person");

            let ptr = Person::into_raw(p) as *mut c_void;
            let pixel_object = pxs_newobject(ptr, free_person, typename);
            let set_name_raw = create_raw_string!("set_name");
            let get_name_raw = create_raw_string!("get_name");
            pxs_object_addfunc(pixel_object, set_name_raw, set_name);
            pxs_object_addfunc(pixel_object, get_name_raw, get_name);
            // Save...
            let var = pxs_newhost(pixel_object);

            free_raw_string!(set_name_raw);
            free_raw_string!(get_name_raw);
            free_raw_string!(typename);
            var
        }
    }

    // Testing callbacks
    pub extern "C" fn print_wrapper(args: *mut pxs_Var) -> *mut pxs_Var {
        unsafe {
            let runtime = pxs_listget(args, 0);

            let mut string = String::new();
            for i in 1..pxs_listlen(args) {
                let var = pxs_tostring(runtime, pxs_listget(args, i));
                if let Ok(s) = (*var).get_string() {
                    string.push_str(format!("{s} ").as_str());
                }
                // pxs_freevar(var);
            }

            println!("From Runtime: {string}");
        }

        pxs_Var::new_null().into_raw()
    }

    pub extern "C" fn add_wrapper(args: *mut pxs_Var) -> *mut pxs_Var {
        // Assumes n1 and n2
        unsafe {
            let n1 = pxs_Var::from_borrow(pxs_listget(args, 1));
            let n2 = pxs_Var::from_borrow(pxs_listget(args, 2));

            pxs_Var::new_i64(n1.value.i64_val + n2.value.i64_val).into_raw()
        }
    }

    pub extern "C" fn sub_wrapper(args: *mut pxs_Var) -> *mut pxs_Var {
        // Assumes n1 and n2
        unsafe {
            let n1 = pxs_Var::from_borrow(pxs_listget(args, 1));
            let n2 = pxs_Var::from_borrow(pxs_listget(args, 2));

            pxs_Var::new_i64(n1.value.i64_val - n2.value.i64_val).into_raw()
        }
    }

    unsafe extern "C" fn file_loader(file_path: *const c_char) -> pxs_VarT {
        let file_path = unsafe { CStr::from_ptr(file_path).to_str().unwrap() };

        if file_path.is_empty() {
            return pxs_newnull();
        }

        let file_exists = std::fs::exists(file_path).unwrap();

        if !file_exists {
            return pxs_newnull();
        }

        // Read file
        let contents = std::fs::read_to_string(file_path).unwrap();

        // Return contents
        pxs_Var::new_string(contents).into_raw()
    }

    unsafe extern "C" fn dir_reader(dir_path: *const c_char) -> pxs_VarT {
        let dir_path = unsafe { CStr::from_ptr(dir_path).to_str().unwrap() };

        if dir_path.is_empty() {
            return pxs_newnull();
        }

        // Check if dir exists
        let dir_exists = std::fs::exists(dir_path).unwrap();
        if !dir_exists {
            return pxs_newnull();
        }

        // Load dir
        let files = std::fs::read_dir(dir_path).unwrap();
        let result = pxs_newlist();

        for f in files {
            let entry = f.unwrap();
            let raw = create_raw_string!(entry.file_name().into_string().unwrap());
            pxs_listadd(result, pxs_newstring(raw));
            unsafe{free_raw_string!(raw);}
        }

        result
    }

    unsafe extern "C" fn call_function(args: pxs_VarT) -> pxs_VarT {
        // Assume 1 is a function
        let func = pxs_listget(args, 1);
        // Check for args
        let argc = pxs_listlen(args);
        let res = if argc > 2 {
            // 2 is args
            pxs_varcall(
                pxs_listget(args, 0),
                func,
                pxs_newcopy(pxs_listget(args, 2)),
            )
        } else {
            pxs_varcall(pxs_listget(args, 0), func, pxs_newlist())
        };

        // Return result!
        res
    }

    fn test_add_module() {
        println!("Inside Test add module");
        pxs_initialize();
        let module_name = create_raw_string!("pxs");
        let module = pxs_newmod(module_name);
        // Save methods
        let add_name = create_raw_string!("add");
        let n1_name = create_raw_string!("n1");
        let n2_name: *mut i8 = create_raw_string!("n2");
        pxs_addfunc(module, add_name, add_wrapper);
        let n1 = pxs_newint(1);
        let n2 = pxs_newint(2);
        pxs_addvar(module, n1_name, n1);
        pxs_addvar(module, n2_name, n2);

        let name = create_raw_string!("print");
        pxs_addfunc(module, name, print_wrapper);
        let var_name = create_raw_string!("name");
        let jordan = create_raw_string!("Jordan C");
        let var = pxs_newstring(jordan);
        pxs_addvar(module, var_name, var);

        let object_name = create_raw_string!("Person");
        pxs_addobject(module, object_name, new_person);

        // Add call
        let call_name = create_raw_string!("call_function");
        pxs_addfunc(module, call_name, call_function);
        unsafe{free_raw_string!(call_name);}

        // Add a inner module
        let math_module_name = create_raw_string!("math");
        let math_module = pxs_newmod(math_module_name);

        // Add a sub function
        let sub_name = create_raw_string!("sub");
        let zero_name = create_raw_string!("ZERO");
        let diary_name = create_raw_string!("Diary");
        let diary_owner_name = create_raw_string!("DiaryOwner");
        pxs_addobject(math_module, diary_owner_name, new_diary_owner);
        pxs_addobject(math_module, diary_name, new_diary);
        pxs_addfunc(math_module, sub_name, sub_wrapper);
        pxs_addvar(math_module, zero_name, pxs_newint(0));
        let ddiary_name = create_raw_string!("DDiary");
        let diary_item_name = create_raw_string!("DiaryItem");
        pxs_addobject(math_module, diary_item_name, new_diary_item);

        let args = pxs_newlist();
        pxs_listadd(args, pxs_Var::new_string("Test".to_string()).into_raw());
        let args_len = pxs_listlen(args);
        println!("Args len: {args_len}");
        let downer_factory = pxs_newfactory(new_diary_owner, args);
        let diary_args = pxs_newlist();
        pxs_listadd(diary_args, downer_factory);
        let diary_items = vec![
            DiaryItem{
                text: "Test".to_string()
            },
            // DiaryItem{
            //     text: "Text2".to_string()
            // }
        ];
        let item_args = pxs_newlist();
        for item in diary_items {
            let text = pxs_Var::new_string(item.text.clone());
            let factory_args = pxs_newlist();
            pxs_listadd(factory_args, text.into_raw());
            pxs_listadd(item_args, pxs_newfactory(new_diary_item, factory_args));
        }
        pxs_listadd(diary_args, item_args);
        pxs_addvar(math_module, ddiary_name, pxs_newfactory(new_diary, diary_args));

        pxs_add_submod(module, math_module);
        pxs_addmod(module);

        unsafe {
        free_raw_string!(diary_item_name);
        free_raw_string!(diary_owner_name);
        free_raw_string!(ddiary_name);
        free_raw_string!(diary_name);
        free_raw_string!(zero_name);
        free_raw_string!(module_name);
        free_raw_string!(add_name);
        free_raw_string!(n1_name);
        free_raw_string!(n2_name);
        free_raw_string!(object_name);
        free_raw_string!(name);
        free_raw_string!(var_name);
        free_raw_string!(math_module_name);
        free_raw_string!(sub_name);
        }
    }
    fn print_helper(lang: &str) {
        println!("====================== {lang} ===================");
    }

    #[test]
    fn test_execute() {
        println!("Test starting");
        pxs_initialize();

        test_add_module();

        pxs_set_filereader(file_loader);
        pxs_set_dirreader(dir_reader);

        print_helper("Python");
        // 5
        let py_code = r#"
import pxs
from pad.ft_object import function_from_outside 
from pxs.math import *

print(f"DDiary: {DDiary}")
diary = Diary(DiaryOwner("Jordan"), [DiaryItem("Item uno")])
diary.add_item("Yo test dog")
print(diary)
pxs.print(__name__)

function_from_outside() # Should print something

msg = "Welcome " + pxs.name
pxs.print(msg)

result = pxs.add(pxs.n1, pxs.n2)
pxs.print(f"Module result: {result}")

if result != 3:
    raise "Math, Expected 3, got " + str(result)

res = pxs.math.sub(2, 1)
pxs.print(res)
if res != 1:
    raise Exception("Math, Expected 1, got " + str(res))

zero = pxs.math.ZERO
if zero != 0:
    raise Exception("Math, Expected 0, got " + str(zero))

person = pxs.Person("Jordan")
person2 = pxs.Person("Evelyn")
pxs.print(person2.get_name())
pxs.print(person)
print(person.get_name())
person.set_name("Jordan Castro")
print(person.get_name())

print(type(person).__name__)
print(type(pxs.Person).__name__)

def hadd(n1, n2):
    return n1 + n2

print(pxs.call_function(hadd, [1,2]))

def get_pi():
    return 3.1459

print(pxs.call_function(get_pi))
        "#;
        let res = execute_code(py_code, "file_name", shared::pxs_Runtime::pxs_Python);
        assert!(res.is_null(), "Python Error is not empty: {:#?}", res);
        // 3
        print_helper("Lua");
        let lua_code = r#"
local pxs = require('pxs')
local pxs_math = require('pxs.math')

pxs.print("DDiary: " .. tostring(pxs_math.DDiary))

local diary = pxs_math.Diary(pxs_math.DiaryOwner("Jordan"), pxs_math.DiaryItem("Item uno"))
diary:add_item("Yo test dog")
pxs.print(diary)

local ft_object = require('pad/ft_object.lua')
ft_object.function_from_outside()

local msg = "Welcome " .. pxs.name
pxs.print(msg)

local result = pxs.add(pxs.n1, pxs.n2)
pxs.print("Module result: " .. tostring(result))
        "#;
        let res = execute_code(lua_code, "file_name", shared::pxs_Runtime::pxs_Lua);
        assert!(res.is_null(), "Lua Error is not empty: {:#?}", res);

        print_helper("JS");
        let js_code = r#"
import * as pxs from 'pxs';
import * as pxs_math from 'pxs.math';
import * as ft_object from 'pad/ft_object.js';

pxs.print("DDiary: " + pxs_math.DDiary);

let diary = pxs_math.Diary(pxs_math.DiaryOwner("Jordan"), pxs_math.DiaryItem("Item Uno"));
diary.add_item("Yo test dog");
pxs.print(diary);

ft_object.function_from_outside();

let msg = `Welcome ${pxs.name}`;
pxs.print(msg);

let result = pxs.add(pxs.n1, pxs.n2);
pxs.print("Module result: " + result.toString());
"#;
        let res = execute_code(js_code, "file_name", shared::pxs_Runtime::pxs_JavaScript);
        assert!(res.is_null(), "JS Error is not empty: {:#?}", res);

        pxs_finalize();
    }
}
