"""
Entry point for the NEXUS AUTOPARTS Pick/VT220-style console application.

Usage:
    python -m console              # via package
    python -m console.main         # via module
    python console/main.py         # direct
"""

import argparse
import sys

from sqlalchemy import text

from console.config import VERSION, APP_NAME, APP_SUBTITLE, DB_URL


def parse_args(argv=None):
    """Parse command-line arguments."""
    parser = argparse.ArgumentParser(
        prog=APP_NAME.lower(),
        description=f"{APP_NAME} - {APP_SUBTITLE}",
    )
    parser.add_argument(
        "--version",
        action="version",
        version=f"{APP_NAME} {VERSION}",
    )
    parser.add_argument(
        "--db",
        default=DB_URL,
        help="PostgreSQL connection URL (default: from config)",
    )
    return parser.parse_args(argv)


def _print_banner(db_url):
    """Print a startup banner before entering terminal mode."""
    # Mask password in display
    display_url = db_url
    if '@' in db_url:
        pre_at = db_url.split('@')[0]
        post_at = db_url.split('@', 1)[1]
        if ':' in pre_at.split('//')[-1]:
            user = pre_at.split('//')[-1].split(':')[0]
            display_url = f"postgresql://{user}:****@{post_at}"

    border = "=" * 58
    print(border)
    print(f"  {APP_NAME} v{VERSION}")
    print(f"  {APP_SUBTITLE}")
    print(border)
    print(f"  DB : {display_url}")
    print(border)
    print()


def main(argv=None):
    """Main entry point: parse args, set up renderer, DB, and launch the app."""
    args = parse_args(argv)

    db_url = args.db

    # Lazy imports so the module can be loaded without curses available
    # (e.g. during tests or when just checking --version).
    from console.db import Database
    from console.renderers.curses_renderer import CursesRenderer
    from console.core.app import App

    # Print startup banner
    _print_banner(db_url)

    # Test database connection before entering curses mode
    db = Database(db_url)
    try:
        db._get_engine()
        session = db._session()
        session.execute(text("SELECT 1"))
        session.close()
    except Exception as e:
        print(
            f"Error: Cannot connect to database.\n"
            f"\n"
            f"  URL: {db_url}\n"
            f"  Error: {e}\n"
            f"\n"
            f"Make sure PostgreSQL is running and the connection URL is correct.\n"
            f"You can specify a custom URL with the --db flag:\n"
            f"\n"
            f"    python -m console --db postgresql://user:pass@host/dbname\n",
            file=sys.stderr,
        )
        sys.exit(1)

    renderer = CursesRenderer()
    app = App(renderer=renderer, db=db)

    try:
        app.run()
    except KeyboardInterrupt:
        pass
    except Exception as e:
        # Ensure terminal is restored before printing the traceback
        try:
            renderer.cleanup()
        except Exception:
            pass
        print(f"\nError: {e}", file=sys.stderr)
        sys.exit(1)


if __name__ == "__main__":
    main()
