import argparse
import uuid
from pathlib import Path
from typing import List

import ee.tools
from ee.tools import parse_bool
from ee.project import Project


def init_kicad_project(basedir: Path, project: Project, args):
    pro_files: List[Path] = [f for f in basedir.iterdir() if f.name.endswith(".pro")]

    if len(pro_files) == 0:
        return

    cfg = project.get_or_create_section("kicad-project")

    if len(pro_files) == 1:
        pro_file = pro_files[0]
        sch_file: Path = pro_file.parent / (pro_file.name[0:-4] + ".sch")
        pcb_file: Path = pro_file.parent / (pro_file.name[0:-4] + ".kicad_pcb")

        cfg["uuid"] = cfg.get("uuid", str(uuid.uuid4()))

        if sch_file.is_file():
            print("Found KiCAD project and schematic")
            cfg["sch"] = str(sch_file)

        if pcb_file.is_file():
            cfg["pcb"] = str(pcb_file)

        cfg["functions"] = cfg.get("functions", "ee.kicad.functions.default")
        cfg["function-arguments"] = cfg.get("function-arguments", "ee.kicad.functions.default")
    else:
        print("Found more than one kicad project file.")

    if args.kicad_bom_strategy:
        cfg["strategy"] = args.kicad_bom_strategy


def init_digikey(project: Project):
    supplier = project.get_or_create_section("supplier:digikey")

    supplier["function"] = supplier.get("function", "ee.digikey.functions.default")


def init_seeed_opl(project: Project):
    import ee.supplier.seeed
    ee.supplier.seeed.init_project(project)


def init_odoo(project: Project, args):
    enabled = parse_bool(project.cfg.get("odoo", "enabled", fallback=False))
    # print("odoo enabled: {}".format(enabled))

    if args.enable_odoo is not None:
        # print("using args: {}".format(args.enable_odoo))
        enabled = args.enable_odoo

    if not enabled:
        if "odoo" not in project.cfg:
            return
        project.cfg["odoo"]["enabled"] = "no"
        return

    import ee.odoo
    ee.odoo.init_project(project)


def init(project_dir: Path, basedir: Path, args):
    project = Project.load(project_dir)

    init_kicad_project(basedir, project, args)
    init_digikey(project)
    init_seeed_opl(project)
    init_odoo(project, args)

    if args.create_bom_strategy:
        create_bom = project.get_or_create_section("create-bom")
        create_bom["strategy"] = args.create_bom_strategy

    print("Saving project. Now run 'ee ninja' to generate Ninja build file")
    project.save()


parser = argparse.ArgumentParser()
ee.tools.add_default_argparse_group(parser)

parser.add_argument("--basedir",
                    metavar="DIR")

parser.add_argument("--kicad-bom-strategy",
                    required=False,
                    metavar="PY CALLABLE")

parser.add_argument("--create-bom-strategy",
                    required=False,
                    metavar="PY CALLABLE")

parser.add_argument("--enable-odoo",
                    type=parse_bool, nargs="?",
                    const=True, default=None,
                    metavar="BOOL")

args = parser.parse_args()
ee.tools.process_default_argparse_group(args)

if not args.basedir:
    args.basedir = "."

init(Path("."), Path(args.basedir), args)