#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import json
from datetime import datetime

PROJECT_ROOT = os.getcwd()
OUTPUT_DIR = os.path.join(PROJECT_ROOT, "audit")

if not os.path.exists(OUTPUT_DIR):
    os.makedirs(OUTPUT_DIR)

RESULT = {
    "project_root": PROJECT_ROOT,
    "scan_date": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
    "summary": {},
    "files": {
        "controllers": [],
        "models": [],
        "views": [],
        "css": [],
        "javascript": [],
        "routes": [],
        "config": [],
        "migrations": []
    }
}

IGNORE = {
    ".git",
    "vendor",
    "node_modules",
    "storage",
    "__pycache__"
}


def ignored(path):
    for item in IGNORE:
        if item in path.split(os.sep):
            return True
    return False


for root, dirs, files in os.walk(PROJECT_ROOT):

    dirs[:] = [d for d in dirs if d not in IGNORE]

    if ignored(root):
        continue

    for file in files:

        path = os.path.join(root, file)
        rel = os.path.relpath(path, PROJECT_ROOT)

        if file.endswith("Controller.php"):
            RESULT["files"]["controllers"].append(rel)

        elif "/Models/" in rel or "\\Models\\" in rel:
            if file.endswith(".php"):
                RESULT["files"]["models"].append(rel)

        elif file.endswith(".blade.php"):
            RESULT["files"]["views"].append(rel)

        elif file.endswith(".css"):
            RESULT["files"]["css"].append(rel)

        elif file.endswith(".js"):
            RESULT["files"]["javascript"].append(rel)

        elif rel.startswith("routes"):
            RESULT["files"]["routes"].append(rel)

        elif rel.startswith("config"):
            RESULT["files"]["config"].append(rel)

        elif "migrations" in rel:
            RESULT["files"]["migrations"].append(rel)

RESULT["summary"] = {
    "controllers": len(RESULT["files"]["controllers"]),
    "models": len(RESULT["files"]["models"]),
    "views": len(RESULT["files"]["views"]),
    "css": len(RESULT["files"]["css"]),
    "javascript": len(RESULT["files"]["javascript"]),
    "routes": len(RESULT["files"]["routes"]),
    "config": len(RESULT["files"]["config"]),
    "migrations": len(RESULT["files"]["migrations"])
}

output = os.path.join(OUTPUT_DIR, "architecture.json")

with open(output, "w") as f:
    json.dump(RESULT, f, indent=4)

print("=" * 60)
print("DOOCTOR DEVKIT - SCANNER V1")
print("=" * 60)

for key, value in RESULT["summary"].items():
    print("{:<15} {}".format(key + ":", value))

print()
print("Audit enregistré dans :")
print(output)
