import sys
import importlib
from pathlib import Path

import fire


class LoggingCLI:
    """Centralized CLI for scripts in the 'sieve_logging/scripts/' directory."""

    def __init__(self):
        self.scripts_dir = Path(__file__).parent / "scripts"

    def list(self):
        """List all available scripts."""
        scripts = [
            p.stem for p in self.scripts_dir.glob("*.py") if not p.name.startswith("_")
        ]
        return scripts

    def run(self, script_name: str, *args):
        """
        Run a specific script by name.

        Args:
            script_name (str): The name of the script (without `.py`).
            *args: Arguments to pass to the script's `main()` function.
        """
        try:
            # Dynamically import the requested script
            module = importlib.import_module(f"sieve_logging.scripts.{script_name}")
        except ModuleNotFoundError:
            print(f"Error: Script '{script_name}' not found.")
            print("Available scripts:", ", ".join(self.list()))
            sys.exit(1)

        # Ensure the script has a `main()` function
        if not hasattr(module, "main"):
            print(f"Error: Script '{script_name}' does not have a 'main()' function.")
            sys.exit(1)

        # Execute the `main()` function of the script
        fire.Fire(module.main)

    def __call__(self, *args):
        """Fallback to run if a script name is passed as the first argument."""
        if not args:
            print("Usage: sieve-logging <SCRIPT> [ARGS]")
            print("Available scripts:")
            for script in self.list():
                print(f"  - {script}")
            sys.exit(1)
        self.run(*args)


def main():
    fire.Fire(LoggingCLI)
