import json
import os

MAP_DIR = "lms"
OUTPUT_DIR = "recovered-src"

os.makedirs(OUTPUT_DIR, exist_ok=True)

for map_file in os.listdir(MAP_DIR):
    if not map_file.endswith(".map"):
        continue

    print("Processing:", map_file)

    try:
        with open(os.path.join(MAP_DIR, map_file), "r", encoding="utf-8") as f:
            data = json.load(f)

        sources = data.get("sources", [])
        contents = data.get("sourcesContent", [])

        for source, content in zip(sources, contents):

            if not content:
                continue

            source = source.replace("webpack:///", "")
            source = source.replace("webpack://", "")
            source = source.lstrip("./")

            target = os.path.join(OUTPUT_DIR, source)

            os.makedirs(os.path.dirname(target), exist_ok=True)

            with open(target, "w", encoding="utf-8") as out:
                out.write(content)

    except Exception as e:
        print("Failed:", map_file, e)

print("Recovery Complete")
