import os
import json
import hashlib
from datetime import datetime

# Define the folder structure based on your requirements
FOLDERS = {
    "windows": ["Windows/AircraftModels", "Windows/Configs"],
    "mobile": ["Mobile/AircraftModels", "Mobile/Configs"]
}

def get_file_modification_version(file_path):
    """Get the last modified time of the file as a version string."""
    mtime = os.path.getmtime(file_path)
    return datetime.fromtimestamp(mtime).strftime("%Y%m%d_%H%M%S")

def compute_sha256(file_path):
    """Compute SHA256 hash of a file."""
    sha256 = hashlib.sha256()
    try:
        with open(file_path, "rb") as f:
            for chunk in iter(lambda: f.read(4096), b""):
                sha256.update(chunk)
        return sha256.hexdigest()
    except Exception as e:
        return f"Error: {e}"

def generate_platform_manifest(platform_name):
    print(f"🚀 Generating manifest for: {platform_name.upper()}...")
    
    # Create the file list for this specific platform (Platform + Common)
    target_folders = FOLDERS[platform_name]
    
    manifest = {
        "platform": platform_name,
        "manifestVersion": datetime.now().strftime("%Y%m%d_%H%M%S"),
        "entries": []
    }

    for folder in target_folders:
        if not os.path.exists(folder):
            print(f"⚠️  Warning: Folder '{folder}' not found. Skipping...")
            continue

        # os.walk handles subdirectories inside Models or Artworks
        for root, _, files in os.walk(folder):
            for file in files:
                file_path = os.path.join(root, file)
                
                # Normalize path for the JSON (replaces backslashes for web/url compatibility)
                display_path = file_path.replace("\\", "/")
                
                size = os.path.getsize(file_path)
                sha_hash = compute_sha256(file_path)
                file_version = get_file_modification_version(file_path)

                manifest["entries"].append({
                    "name": file,
                    "path": display_path,
                    "size": size,
                    "hash": sha_hash,
                    "version": file_version
                })
                print(f"   ✔ {file}")

    output_file = f"manifest_{platform_name}.json"
    with open(output_file, "w") as f:
        json.dump(manifest, f, indent=4)
    
    print(f"💾 Saved to {output_file}\n")

if __name__ == "__main__":
    # 1. Generate PC Manifest
    generate_platform_manifest("windows")
    
    # 2. Generate Mobile Manifest
    generate_platform_manifest("mobile")
    
    print("✨ All manifests are up to date.")
