from pathlib import Path
from datetime import date
import json
import re

API_FOLDER = "gateway/api"


def extract_description(text):
    """
    Reads the first block comment or // comment.
    """

    block = re.search(r"/\*\*(.*?)\*/", text, re.S)

    if block:
        lines = []

        for line in block.group(1).splitlines():
            line = line.strip()
            line = line.lstrip("*").strip()

            if line:
                lines.append(line)

        return " ".join(lines)

    single = re.search(r"//(.*)", text)

    if single:
        return single.group(1).strip()

    return ""


def discover(root):

    root = Path(root)

    api = root / API_FOLDER

    endpoints = []

    if not api.exists():
        raise Exception(f"{api} not found")

    for php in sorted(api.glob("*.php")):

        text = php.read_text(
            encoding="utf8",
            errors="ignore"
        )

        endpoints.append({

            "name":
                php.stem,

            "file":
                str(
                    php.relative_to(root)
                ).replace("\\","/"),

            "endpoint":
                "/gateway/api/" + php.stem + ".php",

            "description":
                extract_description(text)

        })

    return endpoints

def write_registry(root, endpoints):

    registry = Path(root) / "gateway" / "endpoints.txt"

    today = date.today().isoformat()

    with registry.open(
        "w",
        encoding="utf8"
    ) as f:
        
        f.write(f"""============================================================
        Gateway Endpoint Registry
        ============================================================

        Gateway Version:
        MVP

        Created:
        {today}

        Last Updated:
        {today}

        Purpose:
        Authoritative registry of all Gateway HTTP endpoints.

        Notes:
        Only document implemented endpoints.
        Do not document planned endpoints.
        Update this file whenever an endpoint is added, removed or modified.

        ============================================================
        Project
        ============================================================

        Project Root:
        {root}

        Gateway Folder:
        gateway/

        Registry File:
        gateway/endpoints.txt

        ============================================================
        Registered Endpoints
        ============================================================
        """
                )

        for ep in endpoints:

            f.write(
f"""
------------------------------------------------------------
Name:
{ep["name"]}

Method:
GET

URL:
{ep["endpoint"]}

PHP File:
{ep["file"]}

Purpose:
{ep["description"]}

Status:
Not Reviewed

Last Reviewed:
{today}

Notes:

------------------------------------------------------------
"""
            )


if __name__ == "__main__":

    #
    # CHANGE THIS
    #

    PROJECT = r"D:\xampp\htdocs\manyfest\ExplorerAssistGPT"

    endpoints = discover(PROJECT)

    output = {

        "service": "Gateway",

        "endpointCount":
            len(endpoints),

        "endpoints":
            endpoints

    }

    write_registry(PROJECT, endpoints)

    reports = (
        Path(PROJECT)
        / "reports"
        / "discovery"
    )

    reports.mkdir(
        parents=True,
        exist_ok=True
    )

    outfile = (
        reports
        / "endpoint_inventory.json"
    )

    outfile.write_text(

        json.dumps(
            output,
            indent=4
        ),

        encoding="utf8"

    )

    print()

    print("Gateway discovery complete.")

    print()

    print(f"Inventory written to: {outfile}")

    print(f"Registry written to : {Path(PROJECT) / 'gateway' / 'endpoints.txt'}")

    print()

    print(json.dumps(
        output,
        indent=4
    ))