"""Command-line interface for cheatly."""

import argparse
import logging
import sys

from rich.console import Console

from .config import Config
from .core.environment import Environment
from .core.pipeline import RenderPipeline
from .displays import LiveDisplay, StaticDisplay
from .validator import Validator


def main() -> None:
    """Main CLI entry point.

    Parses command-line arguments and executes the appropriate display mode.
    Supports static display, live tracking, sheet validation, and debugging.

    Returns:
        None

    Raises:
        KeyboardInterrupt: User interrupted with Ctrl+C
        SystemExit: Validation mode exits with status code
    """
    parser = argparse.ArgumentParser(
        prog="termcards", description="Context-aware cheatsheet viewer"
    )

    parser.add_argument(
        "--sheet", help="Specific sheet to display (e.g., tmux, micro, python)"
    )
    parser.add_argument("--pane", help="Tmux pane ID to inspect (e.g., %%26)")
    parser.add_argument(
        "--focus", help="Focus on specific context (defaults to innermost)"
    )

    parser.add_argument(
        "--mode",
        choices=["reference", "code"],
        default="reference",
        help="Display mode: reference (shortcuts/commands) or code (examples)",
    )
    parser.add_argument(
        "--live",
        action="store_true",
        help="Live mode - continuously track active pane and update display",
    )

    parser.add_argument(
        "--check",
        nargs="*",
        metavar="PATH",
        help="Validate sheet dimensions (defaults to sheets directory if no paths given)",
        default=argparse.SUPPRESS,
    )

    parser.add_argument("--debug", action="store_true", help="Show debug information")

    args = parser.parse_args()

    if args.debug:
        logging.basicConfig(
            level=logging.DEBUG, format="%(name)s:%(lineno)d - %(message)s"
        )

    if hasattr(args, "check"):
        validator = Validator()
        paths = args.check or [Config.SHEETS_DIR]
        success = validator.validate_paths(paths)
        sys.exit(0 if success else 1)

    console = Console()
    pipeline = RenderPipeline()

    if args.live and not args.pane:
        env = Environment.from_system(pane_id="")
        env.pane_id = None
    else:
        env = Environment.from_system(pane_id=args.pane)

    try:
        if args.live:
            display = LiveDisplay(pipeline, console)
            display.show(env, mode=args.mode, focus=args.focus, debug=args.debug)
        else:
            display = StaticDisplay(console)
            view = pipeline.render(
                env,
                mode=args.mode,
                focus=args.focus,
                debug=args.debug,
                specific_sheet=args.sheet,
            )
            display.show(view)

    except KeyboardInterrupt:
        sys.exit(0)
    except Exception as e:
        if args.debug:
            raise
        console.print(f"[red]Error: {e}[/red]")
        sys.exit(1)


if __name__ == "__main__":
    main()
