import { createContext, useContext, useEffect, useState } from "react";
import  { BaseDirectory, readTextFile, exists, writeTextFile, mkdir } from "@tauri-apps/plugin-fs";
import { ParamKeys } from "./system_prompt";
import { path } from '@tauri-apps/api';
import { openPath } from '@tauri-apps/plugin-opener';

const dataContext=createContext();


const filePath= 'param.json';

export function DataProvider({children}) {

    const [data, setData] = useState(null);

    async function read(){

        try{

            const folder=await path.appDataDir();
            if (!(await exists(folder))) {        
                
                console.log('Creating folder:', folder);
                await mkdir(folder);
            }

            const contents=await readTextFile(filePath, { baseDir: BaseDirectory.AppData });
            let output=await JSON.parse(contents);


            // check if all keys in ParamKeys are present in output
            const missingKeys = ParamKeys.filter(key => !output.hasOwnProperty(key));
            if(missingKeys.length > 0){
                console.warn("Missing keys in output:", missingKeys);
                // Fill missing keys with default values
                missingKeys.forEach(key => {
                    output[key] = params[key] || ""; // Use params[key] as default value
                });
            }
            
            console.log("File read successfully:", output);

            return output; 

        }catch(error){
            console.error("Error reading file:", error);
            return null; // Return null if reading fails
        }
        
        
    }
    async function write(towrite){

        // let towrite=data;
        if(!towrite){
            const res=await fetch('default.json');
            towrite=await res.json();            
            setData(towrite);                     
        }
        
        try{                
            const folder = await path.appDataDir();
            const res_write=await writeTextFile(`${folder}\\${filePath}`, JSON.stringify(towrite))
            console.log("File written successfully", `${folder}\\${filePath}`);
        }catch(error){
            console.error("Error writing file:", error);
        }

    }

    useEffect(()=>{
        read().then(data_ => {
            if(data_){
                setData(data_);
            } else {
                write(); // Write default data if read fails
            }
        }).catch(error => {
            console.error("Error in useEffect:", error);
        });
    },[])


    return (
        <dataContext.Provider value={{
            data,
            read,
            write,              
            openFile: async () => {
                const folder = await path.appDataDir();
                const file = await path.join(folder, filePath);
                await openPath(file);
            },
        }}>
            {children}
        </dataContext.Provider>
    );
}

export function useData() {
    const context = useContext(dataContext);
    if (!context) {
        throw new Error("useData must be used within a DataProvider");
    }
    return context;
}