"""Cross-platform console screen clearing utility."""

from __future__ import annotations

import argparse
import logging
import platform
import subprocess

logger = logging.getLogger(__name__)

IS_WINDOWS = platform.system() == "Windows"


def clear_screen() -> None:
    """Clear the console screen cross-platform.

    Uses 'cls' command on Windows and 'clear' command on Unix-like systems.
    Also attempts to use ANSI escape codes for better compatibility.
    """
    try:
        # Try ANSI escape code first (works on most modern terminals)
        print("\033[2J\033[H", end="")

        # Then use system command for guaranteed clearing
        if IS_WINDOWS:
            logger.debug("Executing Windows cls command")
            subprocess.run(["cmd", "/c", "cls"], check=True)
        else:
            logger.debug("Executing Unix clear command")
            subprocess.run(["clear"], check=True)

        logger.info("Screen cleared successfully")

    except subprocess.CalledProcessError as e:
        logger.error(f"Failed to clear screen: {e.__class__.__name__}")
        raise
    except OSError as e:
        logger.error(f"OS error while clearing screen: {e.__class__.__name__}")
        raise


def main() -> None:
    """Run entry point for the command-line interface."""
    parser = argparse.ArgumentParser(
        description="Cross-platform console screen clearing utility",
        epilog="Examples:\n  clear\n  clear --debug",
    )
    parser.add_argument(
        "--debug",
        "-d",
        action="store_true",
        help="Enable debug logging for detailed output",
    )

    args = parser.parse_args()

    if args.debug:
        logging.basicConfig(level=logging.DEBUG, format="%(levelname)s: %(message)s")
        logger.debug("Debug mode enabled")
        logger.debug(f"Platform: {platform.system()} {platform.version()}")
        logger.debug(f"Python version: {platform.python_version()}")
    else:
        logging.basicConfig(level=logging.INFO, format="%(message)s")

    try:
        clear_screen()
    except Exception as e:
        logger.error(f"Error: {e}")
        return 1

    return 0


if __name__ == "__main__":
    exit(main())
