"""Main CLI entry point for the rclone manager application."""

import click
import curses
import sys
import time
from importlib.metadata import version as pkg_version
from typing import List, Optional

from jusfltuls.rclone_scanner import list_remotes
from jusfltuls.mcrc_ui import RcloneManagerUI


def _get_provider_color_code(remote: str) -> str:
    """Get ANSI color code for a remote provider.

    Args:
        remote: Remote name (e.g., "onedrive:", "mega:")

    Returns:
        ANSI color code string
    """
    # ANSI color codes
    BLUE = "\033[34m"
    GREEN = "\033[32m"
    RED = "\033[31m"
    CYAN = "\033[36m"
    RESET = "\033[0m"

    provider = remote.rstrip(":").lower()

    if provider == "onedrive":
        return BLUE
    elif provider == "drime":
        return GREEN
    elif provider == "mega":
        return RED
    elif provider == "pcloud":
        return CYAN
    else:
        return ""


def select_remote(remotes: List[str]) -> Optional[str]:
    """Let the user select a remote if there are multiple."""
    if not remotes:
        print(
            "Error: No rclone remotes found. Please configure one using 'rclone config'.",
            file=sys.stderr,
        )
        return None

    if len(remotes) == 1:
        return remotes[0]

    print("\nMultiple rclone remotes found:\n")
    for i, remote in enumerate(remotes):
        color = _get_provider_color_code(remote)
        reset = "\033[0m" if color else ""
        print(f"  {i + 1}. {color}{remote}{reset}")

    while True:
        try:
            choice = input(f"\nSelect remote (1-{len(remotes)}): ").strip()
            if not choice:
                continue
            idx = int(choice) - 1
            if 0 <= idx < len(remotes):
                return remotes[idx]
            else:
                print(f"Please enter a number between 1 and {len(remotes)}.")
        except ValueError:
            print("Invalid input. Please enter a number.")
        except (EOFError, KeyboardInterrupt):
            return None


def run_ui(stdscr, remote_name: str) -> None:
    """Main UI loop using curses."""
    # REMOVED: os.system('stty sane') here.
    # Calling it inside curses.wrapper breaks the curses terminal state.

    ui = RcloneManagerUI(stdscr)
    ui.remote_name = remote_name
    ui.left_panel.is_active = True

    # Initial data load
    ui.update_local()
    ui.update_remote()

    # Draw initial UI
    ui.draw()

    while True:
        # Get user input (non-blocking)
        try:
            key = stdscr.getch()
        except KeyboardInterrupt:
            break

        if key == -1:
            # Small sleep to prevent CPU spinning
            time.sleep(0.01)
            continue

        needs_redraw = False

        # Handle input
        if key == ord("q") or key == ord("Q"):
            break
        elif key == ord("\t") or key == 9:  # Tab key
            ui.switch_panel()
            needs_redraw = True
        elif key == curses.KEY_UP:
            ui.move_up()
            needs_redraw = True
        elif key == curses.KEY_DOWN:
            ui.move_down()
            needs_redraw = True
        elif key == curses.KEY_PPAGE:  # Page Up
            ui.move_pgup()
            needs_redraw = True
        elif key == curses.KEY_NPAGE:  # Page Down
            ui.move_pgdown()
            needs_redraw = True
        elif key == curses.KEY_HOME:
            ui.move_home()
            needs_redraw = True
        elif key == curses.KEY_END:
            ui.move_end()
            needs_redraw = True
        elif key == curses.KEY_LEFT:
            if ui.active_panel == "right":
                ui.switch_panel()
                needs_redraw = True
        elif key == curses.KEY_RIGHT:
            if ui.active_panel == "left":
                ui.switch_panel()
                needs_redraw = True
        elif key in (10, 13, curses.KEY_ENTER):  # Enter key
            ui.handle_enter()
            needs_redraw = True
        elif key == ord("2") or key == curses.KEY_F2:  # F2 Mount
            ui.handle_mount()
            needs_redraw = True
        elif key == ord("4") or key == curses.KEY_F4:  # F4 View
            ui.handle_view()
            needs_redraw = True
        elif key == ord("3") or key == curses.KEY_F3:  # F3 Check
            ui.handle_check()
            needs_redraw = True
        elif key == ord("5") or key == curses.KEY_F5:  # F5 Copy
            ui.handle_copy()
            needs_redraw = True
        elif key == ord("8") or key == curses.KEY_F8:  # F8 Delete
            ui.handle_delete()
            needs_redraw = True
        elif key == ord("9") or key == curses.KEY_F9:  # F9 Sync
            ui.handle_sync()
            needs_redraw = True
        elif key == ord("s") or key == ord("S"):  # Sync
            ui.handle_sync()
            needs_redraw = True
        elif key == ord("b") or key == ord("B"):  # Backup with restic
            ui.handle_backup()
            needs_redraw = True
        elif key == ord("e") or key == ord("E"):  # Extract/Restore with restic
            ui.handle_restore()
            needs_redraw = True
        elif key == ord("p") or key == ord("P"):  # Toggle password mode
            ui.toggle_password_mode()
            needs_redraw = True
        elif key == ord("r") or key == ord("R"):
            ui.update_local()
            ui.update_remote()
            needs_redraw = True
        elif key == ord("h") or key == ord("H") or key == curses.KEY_F1:  # F1 Help
            ui.handle_help()
            needs_redraw = True
        elif key == ord("7"):  # F7 Mkdir (remote only) - handle ESC sequences below
            ui.handle_mkdir()
            needs_redraw = True
        elif key == curses.KEY_RESIZE:  # Terminal resize
            needs_redraw = True
        elif key == 27:  # ESC - might be start of F3 or F7 escape sequence
            # Try to read escape sequence
            time.sleep(0.005)  # Small delay for sequence to arrive
            seq = ""
            for _ in range(4):
                ch = stdscr.getch()
                if ch == -1:
                    break
                if 32 <= ch <= 126:
                    seq += chr(ch)
            if seq in ["[12~"]:  # F2: ESC [ 1 2 ~
                ui.handle_mount()
                needs_redraw = True
            elif seq in ["[14~"]:  # F4: ESC [ 1 4 ~
                ui.handle_view()
                needs_redraw = True
            elif seq in ["[13~"]:  # F3: ESC [ 1 3 ~
                ui.handle_check()
                needs_redraw = True
            elif seq in [
                "[18~",
                "[31~",
            ]:  # F7: ESC [ 1 8 ~ (xterm) or ESC [ 3 1 ~ (vt100)
                ui.handle_mkdir()
                needs_redraw = True

        # Redraw when something changed
        if needs_redraw:
            ui.draw()


def print_version(ctx, param, value):
    """Print version and exit."""
    if not value or ctx.resilient_parsing:
        return
    print(pkg_version("jusfltuls"))
    ctx.exit()


@click.command()
@click.option(
    "--remote",
    "-r",
    help="Rclone remote name to use.",
)
@click.option(
    "--refresh",
    "-f",
    default=0,
    help="Auto-refresh interval in seconds (0 to disable).",
    type=int,
)
@click.option("--debug", "-d", is_flag=True, default=False, help="Enable debug mode.")
@click.option(
    "--version",
    "-v",
    is_flag=True,
    callback=print_version,
    expose_value=False,
    is_eager=True,
    help="Show version and exit.",
)
def main(remote: Optional[str], refresh: int, debug: bool) -> None:
    """
    Midnight Commander-style rclone manager.

    Displays local and remote files in a two-panel interface.
    Navigate with arrow keys, change directories with Enter,
    switch panels with Tab, quit with 'q'.
    """
    # Check rclone version on startup
    from jusfltuls.rclone_scanner import check_rclone_version, prompt_download

    is_ok, version, message = check_rclone_version()
    if not is_ok:
        print(f"Warning: {message}", file=sys.stderr)
        download_url = (
            "https://downloads.rclone.org/v1.73.3/rclone-v1.73.3-linux-amd64.deb"
        )
        if prompt_download("rclone", download_url):
            print("\nPlease install rclone manually from the URL above.")
            print("Then restart mcrc.\n")
        sys.exit(1)
    elif debug:
        print(f"Debug: {message}")

    remotes = list_remotes()

    if remote:
        if remote not in remotes and not remote.endswith(":"):
            if f"{remote}:" in remotes:
                remote = f"{remote}:"
            else:
                print(
                    f"Error: Remote '{remote}' not found in rclone config.",
                    file=sys.stderr,
                )
                sys.exit(1)
        remote_name = remote
    else:
        remote_name = select_remote(remotes)

    if not remote_name:
        sys.exit(1)

    # Ensure remote name ends with :
    if not remote_name.endswith(":"):
        remote_name += ":"

    try:
        # Run the curses UI with refresh interval
        curses.wrapper(lambda stdscr: run_ui(stdscr, remote_name))
    except Exception as e:
        import traceback
        import os

        # Ensure curses is ended and terminal is sane on crash
        try:
            curses.endwin()
        except:
            pass
        os.system("stty sane")
        print("\n" + "=" * 60, file=sys.stderr)
        print("  MCRC CRASHED!", file=sys.stderr)
        print("=" * 60, file=sys.stderr)
        traceback.print_exc(file=sys.stderr)
        print("=" * 60, file=sys.stderr)
        sys.exit(1)


if __name__ == "__main__":
    main()
