import os
import json
import argparse
import httpx


def rebuild_from_sourcemap(source_map_file, destination_dir):
    with open(source_map_file, "r") as f:
        source_map = json.load(f)

    source_map_dir = os.path.dirname(source_map_file)
    source_map_sources = source_map["sources"]
    source_map_sources_content = source_map["sourcesContent"]

    for i, source in enumerate(source_map_sources):
        try:
            source_path = os.path.join(source_map_dir, source)
            source_content = source_map_sources_content[i]

            source_path = os.path.normpath(source_path)
            source_path = source_path.replace("\\", "/").replace("../", "")

            # if the source path is empty, skip it
            if not source_path:
                continue

            dest = os.path.join(destination_dir, source_path)
            if not os.path.exists(os.path.dirname(dest)):
                os.makedirs(os.path.dirname(dest))

            with open(dest, "w") as f:
                f.write(source_content)

            print("Created:", dest)
        except:
            pass

def download_file(url, dest):
    with httpx.stream("GET", url) as response:
        with open(dest, "wb") as f:
            for chunk in response.iter_bytes():
                f.write(chunk)

    print("Downloaded:", dest)
    return dest


def main():
    parser = argparse.ArgumentParser(
        description="Create files from a source mapping file."
    )
    parser.add_argument("source_map_file", type=str, help="Path to the .js.map file")
    parser.add_argument("destination_dir", type=str, help="Destination directory")
    args = parser.parse_args()

    map_file = args.source_map_file
    if map_file.startswith("http"):
        map_file = download_file(args.source_map_file, "source_map.js.map")

    dest = args.destination_dir
    if not os.path.exists(dest):
        os.makedirs(dest)

    rebuild_from_sourcemap(args.source_map_file, args.destination_dir)


if __name__ == "__main__":
    main()