"""Entry point for Ghostty Settings TUI."""

import argparse
import sys
from pathlib import Path

from . import __version__


def parse_args() -> argparse.Namespace:
    """Parse command line arguments."""
    parser = argparse.ArgumentParser(
        prog="ghostty-tui",
        description="TUI application for managing Ghostty terminal settings",
    )

    parser.add_argument(
        "--version", "-V",
        action="version",
        version=f"%(prog)s {__version__}"
    )

    parser.add_argument(
        "--config", "-c",
        type=str,
        default=None,
        help="Path to Ghostty config file (default: ~/.config/ghostty/config)"
    )

    parser.add_argument(
        "--schema-file",
        type=str,
        default=None,
        help="Use schema from file instead of Ghostty CLI (for testing)"
    )

    return parser.parse_args()


def main() -> int:
    """Main entry point."""
    args = parse_args()

    # Validate config path if provided
    if args.config:
        config_path = Path(args.config).expanduser()
        if not config_path.parent.exists():
            print(f"Error: Config directory does not exist: {config_path.parent}", file=sys.stderr)
            return 1

    # Validate schema file if provided
    if args.schema_file:
        schema_path = Path(args.schema_file).expanduser()
        if not schema_path.exists():
            print(f"Error: Schema file not found: {schema_path}", file=sys.stderr)
            return 1

    try:
        from .app import GhosttySettingsTUI

        app = GhosttySettingsTUI(
            config_path=args.config,
            schema_file=args.schema_file
        )
        app.run()
        return 0

    except KeyboardInterrupt:
        print("\nInterrupted", file=sys.stderr)
        return 130
    except Exception as e:
        print(f"Error: {e}", file=sys.stderr)
        return 1


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