import ast
from pathlib import Path

env_file = Path("/home/lpierson/mercier18/modules_OCA.env")
MODULES = set()

for line in env_file.read_text().splitlines():
    line = line.strip()
    if line.startswith("OCA_MODULES="):
        raw = line.split("=", 1)[1]
        MODULES = {m.strip() for m in raw.split(",") if m.strip()}
        break

print(f"→ {len(MODULES)} modules chargés depuis {env_file.name}\n")

IGNORE_ODOO_DEPS = {
    "base", "web", "mail", "account", "sale", "purchase", "stock",
    "hr", "project", "crm", "contacts", "portal", "website",
}

scan_root = Path("/home/lpierson/mercier18/custom")

python_deps = {}
odoo_deps_external = {}   # pas dans MODULES, pas ignoré
odoo_deps_internal = {}   # dans MODULES → déjà couvert
not_found = set(MODULES)

for manifest in sorted(scan_root.rglob("__manifest__.py")):
    module_name = manifest.parent.name
    if module_name not in MODULES:
        continue
    not_found.discard(module_name)
    try:
        data = ast.literal_eval(manifest.read_text())
    except Exception as e:
        print(f"[ERREUR parsing] {module_name}: {e}")
        continue

    ext = data.get("external_dependencies", {})
    for pkg in ext.get("python", []):
        python_deps.setdefault(pkg, []).append(module_name)

    for dep in data.get("depends", []):
        if dep in IGNORE_ODOO_DEPS:
            continue
        if dep in MODULES:
            odoo_deps_internal.setdefault(dep, []).append(module_name)
        else:
            odoo_deps_external.setdefault(dep, []).append(module_name)

print("=" * 65)
print("DÉPENDANCES PYTHON  →  à ajouter dans requirements.txt")
print("=" * 65)
if python_deps:
    for dep, mods in sorted(python_deps.items()):
        print(f"  {dep:<35} ← {', '.join(sorted(mods))}")
else:
    print("  (aucune)")

print()
print("=" * 65)
print("DÉPENDANCES ODOO DÉJÀ DANS LA LISTE  →  ordre d'install OK")
print("=" * 65)
if odoo_deps_internal:
    for dep, mods in sorted(odoo_deps_internal.items()):
        print(f"  {dep:<35} ← requis par : {', '.join(sorted(mods))}")
else:
    print("  (aucune)")

print()
print("=" * 65)
print("DÉPENDANCES ODOO MANQUANTES  →  à ajouter dans OCA_MODULES")
print("=" * 65)
if odoo_deps_external:
    for dep, mods in sorted(odoo_deps_external.items()):
        print(f"  {dep:<35} ← requis par : {', '.join(sorted(mods))}")
else:
    print("  (aucune)")

print()
print("=" * 65)
print("MODULES NON TROUVÉS  →  dépôts OCA pas encore clonés ?")
print("=" * 65)
if not_found:
    for m in sorted(not_found):
        print(f"  {m}")
else:
    print("  (tous trouvés)")

