import { parse as JSONC } from "https://deno.land/x/jsonct@v0.1.0/mod.ts";

type JsonBase = Record<string, string|string[]>
type JsonDeep = Record<string, string|JsonBase>
type JsonLike = JsonDeep

type Configuration = {imports:JsonDeep, compilerOptions:JsonDeep};

export const Root = new URL(`file://${Deno.cwd().replaceAll("\\", "/")}`).toString();
export default async function HuntConfig()
{
    let path:string, json:JsonLike|undefined;

    const loadJSON =async(inPath:string)=>{
        try{
            const resp = await fetch(Root + "/" + inPath);
            if(inPath.endsWith(".jsonc"))
            {
                const text = await resp.text();
                json = JSONC(text) as JsonLike;
            }
            else
            {
                json = await resp.json();
            }
            return json;            
        }
        catch(_e)
        {
            return {};
        }
    }

    try// look for `deno.json`
    {
        json = await loadJSON("deno.json");
    }
    catch(_e)
    {
        
        try // look for `deno.jsonc`
        {
            json = await loadJSON("deno.jsonc");
        }
        catch(_e)
        {
            try // look in the vscode plugin settings
            {
                json = await loadJSON(".vscode/settings.json")
                path = json ? json["deno.config"] as string : "";
                json = undefined;
                if(path)
                {
                    json = await loadJSON(path)
                }
            }
            catch(_e)
            {
                // cant find a config using the vscode plugin
            }
        }
    }

    if(!json)
    {
        json = {};
    }


    path = json.importMap as string;
    if(!json.imports && path)
    {
        json.imports = await loadJSON(path) as Record<string, string>;
    }      

    return json as {imports:JsonDeep, compilerOptions:JsonLike};  

}