#!/usr/bin/env python3
import sys
import os
import argparse

def find_java_version(version):
    if sys.platform == 'darwin':  # macOS
        jvm_dir = '/usr/local/opt'
    else:  # Linux
        jvm_dir = '/usr/lib/jvm'
    
    available_versions = [d for d in os.listdir(jvm_dir) if version in d and os.path.isdir(os.path.join(jvm_dir, d)) and 'jdk' in d]
    
    if not available_versions:
        print(f"Error: Java version {version} not found in {jvm_dir}")
        sys.exit(1)
    
    return os.path.join(jvm_dir, available_versions[0])

if __name__ == '__main__':
    agupa = argparse.ArgumentParser(description='Switch between installed Java versions. Usage: eval $(switch-java <version>)')
    agupa.add_argument('version', help='Java version to switch to')

    args = agupa.parse_args()
    version_path = find_java_version(args.version)
    
    # Create eval script to set JAVA_HOME and update PATH
    java_home = version_path
    new_path = f"{version_path}/bin:{os.getenv('PATH')}"
    
    # Output commands for `eval` to execute
    print(f"export JAVA_HOME='{java_home}'")
    print(f"export PATH='{new_path}'")
