
import os
import shutil
import json

# Paths relative to script execution (run from repo root)
script_dir = os.path.dirname(os.path.abspath(__file__))
repo_root = os.path.dirname(script_dir)
SRC_DIR = os.path.join(repo_root, "src", "odgs")
DEST_DIR = os.path.join(repo_root, "lib", "schemas")

PLANES = ["legislative", "judiciary", "executive"]

def sync_schemas():
    print(f"🔄 Syncing Schemas from {SRC_DIR} to {DEST_DIR}...")
    
    # Ensure destination exists and clean it? 
    # Maybe not clean entire dir if index.js is there manually, but plan says auto-generate index.js
    if not os.path.exists(DEST_DIR):
        os.makedirs(DEST_DIR)

    # Dictionary to hold exports for index.js
    exports = {}

    for plane in PLANES:
        src_plane = os.path.join(SRC_DIR, plane)
        dest_plane = os.path.join(DEST_DIR, plane)
        
        if not os.path.exists(dest_plane):
            os.makedirs(dest_plane)
            
        if os.path.exists(src_plane):
            for file in os.listdir(src_plane):
                if file.endswith(".json"):
                    src_file = os.path.join(src_plane, file)
                    dest_file = os.path.join(dest_plane, file)
                    shutil.copy2(src_file, dest_file)
                    print(f"  ✅ Copied {plane}/{file}")
                    
                    # Track for export
                    key = f"{plane}_{file.replace('.json', '')}"
                    exports[key] = f"./{plane}/{file}"

    # Generate index.js
    index_path = os.path.join(DEST_DIR, "index.js")
    with open(index_path, "w") as f:
        f.write("// Auto-generated by scripts/sync_schemas.py\n\n")
        
        # We can't strict import JSON in ES modules without assertions in some envs
        # But this is likely for a library. 
        # Plan said: "Generates the ../1_NORMATIVE_SPECIFICATION/schemas/index.js exports automatically"
        
        # Let's generate a CJS/ESM compatible export or just list them? 
        # Use require for compatibility if targeting Node CommonJS, or import for ESM.
        # Given 'package.json' type module? 
        # Let's assume standard ESM export from JSON
        
        for key, path in exports.items():
            # import metric from './legislative/standard_metrics.json' 
            # with { type: 'json' }; -> Warning: experimental
            
            # Safer: default export
            f.write(f"import {key} from '{path}' with {{ type: 'json' }};\n")
            
        f.write("\nexport default {\n")
        for key in exports.keys():
            f.write(f"  {key},\n")
        f.write("};\n")
        
    print("✅ Schema Sync Complete.")

if __name__ == "__main__":
    sync_schemas()
