from pathlib import Path
import json

GATEWAY_FOLDER = "gateway"


def discover_gateway(root):

    root = Path(root)

    gateway = root / GATEWAY_FOLDER

    if not gateway.exists():
        raise Exception(f"{gateway} not found")

    api_folder = gateway / "api"

    core_files = []

    for php in sorted(gateway.glob("*.php")):

        core_files.append(php.name)

    api_files = []

    if api_folder.exists():

        for php in sorted(api_folder.glob("*.php")):

            api_files.append(php.name)

    return {

        "gatewayFolder":
            str(gateway.relative_to(root)).replace("\\", "/"),

        "coreFileCount":
            len(core_files),

        "apiEndpointCount":
            len(api_files),

        "coreFiles":
            core_files,

        "apiFiles":
            api_files

    }


if __name__ == "__main__":

    PROJECT = r"D:\xampp\htdocs\manyfest\ExplorerAssistGPT"

    report = discover_gateway(PROJECT)

    reports = (
        Path(PROJECT)
        / "reports"
        / "discovery"
    )

    reports.mkdir(
        parents=True,
        exist_ok=True
    )

    outfile = (
        reports
        / "gateway_inventory.json"
    )

    outfile.write_text(

        json.dumps(
            report,
            indent=4
        ),

        encoding="utf8"

    )

    print()
    print("Gateway inventory complete.")
    print()
    print(f"Inventory written to: {outfile}")
    print()
    print(json.dumps(report, indent=4))