"""CLI entry point for PodangelEX."""

from pathlib import Path
from .functions import read_config, config_menu, run_program, get_config_dir, initialize_workspace


def main():
    """Main CLI entry point."""
    config_dir = get_config_dir()
    config_path = config_dir / "config.json"
    
    # Initialize workspace (creates directories and default config if needed)
    initialize_workspace(config_dir)
    
    # Try to load existing config
    config_dict = read_config(str(config_path))
    
    # If still no config, create one through menu
    if config_dict is None:
        print("No configuration found. Creating new configuration...")
        config_menu(config_dir)
        config_dict = read_config(str(config_path))
    
    if config_dict is None:
        print("Error: Could not load or create config file")
        exit(1)

    main_loop = True

    while main_loop:
        print("\n\nWelcome to PodAngel CLI!")
        workspace = config_dict.get("file_path", "workspace")
        print(f"Workspace: {workspace}")
        print("\nOptions:")
        print("  (1) Reconfigure")
        print("  (2) Run processing")
        print("  (exit) Quit")
        main_input = input("\nInput: ")
        normalized_input = main_input.lower().strip()

        if normalized_input == "1":
            config_menu(config_dir)
            # Reload config after changes
            config_dict = read_config(str(config_path))

        elif normalized_input == "2":
            # Re-initialize workspace in case config changed
            initialize_workspace(config_dir)
            run_program(config_dict=config_dict, config_dir=config_dir)

        elif normalized_input == "exit":
            main_loop = False
            print("Goodbye!")
            exit(0)

        else:
            print("Invalid input. Please enter 1, 2, or 'exit'")


if __name__ == "__main__":
    main()
