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

import click
import curses
import sys
import time
from typing import List, Optional

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

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):
        print(f"  {i+1}. {remote}")
    
    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('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('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 ["[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()

@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.version_option(version="0.1.0", prog_name="mcrc")
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'.
    """
    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()
