# these are methods related to the generated meta.json
import bpy
import json
import os

from .settings_addon import getAddonPreferences

from .settings_scene import NeedleMainSceneSettings

from .utils_debug import debug_err
from .utils_web_project import getGeneratedDirectory
from .__meta__ import getVersion

def getMeta(projectDirectory:str) -> object | None:
    generatedDir = getGeneratedDirectory(projectDirectory)
    # ensure directory exists
    if not os.path.exists(generatedDir):
        os.makedirs(generatedDir)
    meta_path = generatedDir + "/meta.json"
    if not os.path.exists(meta_path):
        json_data = {
            "gzip": True,
            "useRapier": True
        }
        with open(meta_path, "w") as f:
            write = json.dumps(json_data, indent=4)
            f.write(write)
    
    meta_file = None
    with open(meta_path, "r") as f:
        content = f.read()
        try:
            meta_file = json.loads(content)
        except Exception as e:
            debug_err("Failed to parse meta.json", content, e)
            meta_file = json.loads("{}")
            pass
    return meta_file


def writeMeta(projectDirectory:str, meta:object):
    generatedDir = getGeneratedDirectory(projectDirectory)
    meta_path = generatedDir + "/meta.json"
    serialized = json.dumps(meta, indent=4)
    with open(meta_path, "w") as f:
        f.write(serialized)
        f.close()
    pass

def writeProjectSettings(projectDirectory:str, settings:NeedleMainSceneSettings, targetPlatform:str or None = None):
    blenderVersion = bpy.app.version_string
    meta = getMeta(projectDirectory)
    if meta is None:
        return
    meta["gzip"] = settings.useGzip
    if targetPlatform == "glitch":
        meta["gzip"] = True
    meta["useRapier"] = settings.useRapier
    meta["generator"] = "Needle Engine for Blender " + blenderVersion + " (Addon " + getVersion() + ")"

    meta["meta"] = metaMeta = {}
    # get blender filename without ext
    metaMeta["title"] = bpy.path.basename(bpy.context.blend_data.filepath)
    if(metaMeta["title"].endswith(".blend")):
        metaMeta["title"] = metaMeta["title"][:-6]
    metaMeta["description"] = "Built with Needle Engine for Blender: https://needle.tools"
    metaMeta["image"] = "include/poster.webp"

    license = {}
    addonsettings = getAddonPreferences()
    selected_team = addonsettings.selected_team
    license["team"] = selected_team
    meta["license"] = license

    writeMeta(projectDirectory, meta)
    pass