#!/usr/bin/env python
import os
import sys
import hifiyaml as hy

# Use local package when running from the repo
here = os.path.dirname(os.path.abspath(__file__))
yamltools_path = os.path.join(here, "..")
if os.path.exists(os.path.join(yamltools_path, "yamltools4jedi", "__init__.py")):
    if yamltools_path not in sys.path:
        sys.path.insert(0, yamltools_path)

import yamltools4jedi as yj  # noqa: E402

args = sys.argv
nargs = len(args) - 1
if nargs < 2:
    print(f"{os.path.basename(args[0])} <file> <dump|drop|modify|split|split2|pack> [querystr] [newblock_file]")
    exit()

dedent = os.getenv("YJ_DEDENT", "False").upper() == "TRUE"
split_level = int(os.getenv("YJ_SPLIT_LEVEL", "1"))
listIndent = os.getenv("YJ_LIST_INDENT", "False").upper() == "TRUE"
plain_pack = os.getenv("YJ_PLAIN_PACK", "True").upper() == "TRUE"

newblock_file, querystr, fpath = "", "", ""

yfile = args[1]
operator = args[2]
if nargs > 2:
    querystr = args[3]

if operator == "modify":
    if nargs > 3:
        newblock_file = args[4]
    if not newblock_file:
        print("newblock_file cannot be empty for the modify operator")
    if not querystr:
        print("querystr cannot be empty for the modify operator")
elif operator == "pack":  # pack operator
    dirname = yfile
    if nargs > 2:
        fpath = args[3]

if operator != "pack":
    data = hy.load(yfile)

if operator == "dump":
    hy.dump(data, querystr, do_dedent=dedent)

elif operator == "drop":
    hy.drop(data, querystr)
    hy.dump(data)

elif operator == "modify":
    if os.path.exists(newblock_file):
        newblock = hy.load(newblock_file)
    else:
        newblock = hy.text_to_yblock(newblock_file)
    hy.modify(data, querystr, newblock)
    hy.dump(data)

elif operator == "split":
    yj.split(yfile, level=split_level, do_dedent=dedent)
    print(f"Done, split files are availabe under split{split_level}.{yfile}/")

elif operator == "split1":
    yj.split(yfile, level=1, do_dedent=dedent)
    print(f"Done, split1 files are availabe under split1.{yfile}/")

elif operator == "split2":
    yj.split(yfile, level=2, do_dedent=dedent)
    print(f"Done, split2 files are availabe under split2.{yfile}/")

elif operator == "pack":
    if not fpath:
        fpath = "pack." + dirname.rstrip('/').replace("split.", "")
    yj.pack(dirname, fpath, listIndent=listIndent, plain_pack=plain_pack)
    print(f"Done, the final packed file: {fpath}")

else:
    hy.printd(f"unknown operator: {operator}")
