import os
import shutil

MODULE_MAPPINGS = {
    "invoice": "invoices",
    "partner": "partners",
    "dossier": "dossier",
    "project": "projects",
    "financial": "financial",
    "four_pillars": "financial",
    "evm": "financial",
    "inventory": "inventory",
    "material_price": "inventory",
    "state_price": "inventory",
    "sxd": "inventory",
    "operation": "operations",
    "site": "operations",
    "diary": "operations",
    "equipment": "operations",
    "fuel": "operations",
    "autonomous": "agents",
    "knowledge_agent": "agents",
    "agent_": "agents",
    "llm": "agents",
    "deepseek": "agents",
    "generation": "agents",
    "telegram": "integrations",
    "zalo": "zalo_crm",
    "auth": "auth",
    "desktop": "integrations",
    "cloudflared": "integrations",
    "cad": "takeoff",
    "takeoff": "takeoff",
    "boq": "takeoff",
    "health": "core",
    "erp": "core",
}

def get_module_name(name):
    name_lower = name.lower()
    for keyword, module_name in MODULE_MAPPINGS.items():
        if keyword in name_lower:
            return module_name
    return "core"

import_replacements = {}

os.makedirs("app/modules", exist_ok=True)

# 1. Move Routers
routers_dir = "app/api/routers"
if os.path.exists(routers_dir):
    for item in os.listdir(routers_dir):
        if item.startswith("__") or item == "takeoff": continue
        item_path = os.path.join(routers_dir, item)
        module_name = get_module_name(item)
        
        target_dir = f"app/modules/{module_name}/presentation"
        os.makedirs(target_dir, exist_ok=True)
        
        init_path = f"app/modules/{module_name}/__init__.py"
        if not os.path.exists(init_path):
            with open(init_path, "w", encoding="utf-8") as f:
                f.write(f"""
from fastapi import FastAPI
from app.core.module_framework.registry import ModuleRegistry
import pkgutil
import importlib

def setup_module(app: FastAPI, registry: ModuleRegistry):
    from . import presentation
    for _, name, _ in pkgutil.iter_modules(presentation.__path__):
        mod = importlib.import_module(f"app.modules.{module_name}.presentation.{{name}}")
        if hasattr(mod, "router"):
            app.include_router(mod.router)
""")
            with open(f"app/modules/{module_name}/presentation/__init__.py", "w") as f: f.write("")
            os.makedirs(f"app/modules/{module_name}/application", exist_ok=True)
            with open(f"app/modules/{module_name}/application/__init__.py", "w") as f: f.write("")

        if os.path.isfile(item_path):
            mod_name = item.replace(".py", "")
            import_replacements[f"app.api.routers.{mod_name}"] = f"app.modules.{module_name}.presentation.{mod_name}"
            shutil.move(item_path, os.path.join(target_dir, item))
        else:
            # It's a directory (e.g. invoice_modules)
            import_replacements[f"app.api.routers.{item}"] = f"app.modules.{module_name}.presentation.{item}"
            shutil.move(item_path, os.path.join(target_dir, item))

# 2. Move Services
services_dir = "app/services"
if os.path.exists(services_dir):
    for item in os.listdir(services_dir):
        if item.startswith("__") or item in ["takeoff", "zalo_crm", "drawing_takeoff"]: continue
        item_path = os.path.join(services_dir, item)
        module_name = get_module_name(item)
        
        target_dir = f"app/modules/{module_name}/application"
        os.makedirs(target_dir, exist_ok=True)
        
        if os.path.isfile(item_path):
            mod_name = item.replace(".py", "")
            import_replacements[f"app.services.{mod_name}"] = f"app.modules.{module_name}.application.{mod_name}"
            shutil.move(item_path, os.path.join(target_dir, item))
        else:
            # It's a directory (e.g. llm)
            import_replacements[f"app.services.{item}"] = f"app.modules.{module_name}.application.{item}"
            shutil.move(item_path, os.path.join(target_dir, item))

import json
with open("scripts/replacements.json", "w") as f:
    json.dump(import_replacements, f, indent=4)

print(f"Migration mapped {len(import_replacements)} root items. Applying global replace...")

def replace_in_file(filepath):
    try:
        with open(filepath, "r", encoding="utf-8") as f:
            content = f.read()
        
        new_content = content
        # Sort by length so longer paths are replaced first to prevent partial matches
        for old_import, new_import in sorted(import_replacements.items(), key=lambda x: len(x[0]), reverse=True):
            new_content = new_content.replace(old_import, new_import)
            
        if content != new_content:
            with open(filepath, "w", encoding="utf-8") as f:
                f.write(new_content)
            print(f"Updated {filepath}")
    except Exception as e:
        pass

for root, _, files in os.walk("."):
    if ".venv" in root or "__pycache__" in root or ".git" in root:
        continue
    for file in files:
        if file.endswith(".py"):
            replace_in_file(os.path.join(root, file))

print("Done!")
