import os
import glob
import re
import malcat


key_value_re = re.compile(r"^\s*(category|name|filetype|author|icon)\s*:\s*(.*)$")

def parse_metadata(doc_string):
    res = {}
    rest = []
    for l in doc_string.splitlines():
        l = l.strip()
        m = key_value_re.match(l)
        if m:
            if m.group(2).strip():
                res[m.group(1)] = m.group(2)
        else:
            if rest or l:
                rest.append(l)
    res["description"] = "\n".join(rest)
    return res


def get_scripts(data_dir, user_data_dir, reload_plugins=False):
    scripts = []
    seen = set()
    if user_data_dir and user_data_dir != data_dir:
        toscan = (user_data_dir, data_dir)
    else:
        toscan = (data_dir,)
    for base_path in toscan:
        for fname in glob.glob(os.path.join(base_path, "scripts", "**", "*.py"), recursive=True):
            try:
                with open(fname, "rt", encoding="utf8") as f:
                    code = compile(f.read(), fname, "exec")
                if code.co_consts and type(code.co_consts[0]) == str:
                    metadata = parse_metadata(code.co_consts[0])
                else:
                    metadata = {}
                if not "name" in metadata and not fname.startswith(data_dir):
                    metadata["name"] = os.path.basename(fname)
                if "name" in metadata:
                    size = os.stat(fname).st_size
                    scripts.append((
                        fname,
                        metadata["name"].capitalize(),
                        size,
                        metadata.get("category", "<no category>").lower(),
                        metadata.get("filetype", ""),
                        metadata.get("author", ""),
                        metadata.get("description", ""),
                        metadata.get("icon", "wxART_FIND_SCRIPT"),
                        ))

            except SyntaxError:
                continue
    return scripts


