"""CLI interface for Fedibooster using cyclopts."""

import sys
from pathlib import Path
from typing import Annotated
from typing import Optional

import msgspec.toml
from cyclopts import App
from cyclopts import Parameter
from loguru import logger as log

from fedibooster import __version__
from fedibooster.app import main as app_main


def create_app() -> App:
    """Create and configure the cyclopts application."""
    app = App(
        name="fedibooster",
        help=f"Fedibooster v{__version__} - Boost/reblog posts with specified tags on the Fediverse",
    )

    @app.default
    async def main(
        config_path: Annotated[
            Path,
            Parameter(
                show_default=False,
                help="Path to configuration file (required)",
            ),
        ],
        logging_config: Annotated[
            Optional[Path],
            Parameter(
                name=("-l", "--logging-config"),
                help="Full path to logging configuration file",
            ),
        ] = None,
        max_posts: Annotated[
            Optional[int],
            Parameter(
                help="Maximum number of posts and reblogs before quitting",
            ),
        ] = None,
    ) -> None:
        """Run fedibooster with the specified configuration."""
        # Configure logging if a logging config file is provided
        if logging_config and logging_config.is_file():
            with logging_config.open(mode="rb") as log_config_file:
                logging_config_dict = msgspec.toml.decode(log_config_file.read())

            # Handle sys.stdout sink for compatibility
            for handler in logging_config_dict.get("handlers", []):
                if handler.get("sink") == "sys.stdout":
                    handler["sink"] = sys.stdout

            log.configure(**logging_config_dict)

        # Run the main application
        await app_main(config_path=config_path, max_posts=max_posts)

    return app


def cli_entry_point() -> None:
    """Entry point for the CLI."""
    app = create_app()
    app()


if __name__ == "__main__":
    cli_entry_point()
