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

import click
import curses
import time

#from p20260130_12_kilo01.disk_scanner import scan_disks
#from p20260130_12_kilo01.ui import DiskManagerUI
from jusfltuls.disk_scanner import scan_disks
from jusfltuls.ui import DiskManagerUI


def run_ui(stdscr, refresh_interval: int = 10) -> None:
    """Main UI loop using curses.

    Args:
        stdscr: Curses window object
        refresh_interval: Auto-refresh interval in seconds
    """
    # Initialize UI
    ui = DiskManagerUI(stdscr)
    ui.left_panel.is_active = True

    # Initial disk scan
    disks, error = scan_disks()
    if error:
        ui.set_error(error)
    ui.update_disks(disks)

    # Load health info for all disks on startup
    for idx in range(len(disks)):
        ui.load_disk_health(idx)
    ui._update_left_panel()

    # Draw initial UI
    ui.draw()

    # Track last refresh time
    last_refresh = time.time()

    # Main loop - only redraw on user input or timer
    stdscr.nodelay(True)  # Non-blocking input
    while True:
        # Get user input (non-blocking)
        try:
            key = stdscr.getch()
        except KeyboardInterrupt:
            break

        # Check for auto-refresh
        current_time = time.time()
        needs_redraw = False

        if refresh_interval > 0 and (current_time - last_refresh) >= refresh_interval:
            # Auto-refresh: reload health info for all disks and update scrub status
            ui.set_status("refresh")
            for idx in range(len(ui.disks)):
                ui.load_disk_health(idx)
            ui._update_left_panel()
            ui.update_scrub_status()
            ui._update_all_partitions_panel()
            last_refresh = current_time
            needs_redraw = True

        # Also update scrub status on every keypress for responsiveness
        if key != -1:
            ui.update_scrub_status()

        # Handle input
        if key == ord('q') or key == ord('Q'):
            break
        elif key == ord('r') or key == ord('R'):
            # Manual refresh - reload health info for all disks to update test progress
            disks, error = scan_disks()
            if error:
                ui.set_error(error)
            else:
                ui.clear_messages()
            ui.update_disks(disks)
            # Reload health info for all disks to get updated test progress
            for idx in range(len(disks)):
                ui.load_disk_health(idx)
            ui._update_left_panel()
            needs_redraw = True
        elif key == ord('h') or key == ord('H'):
            # Load health info for selected disk
            if ui.active_panel == "left":
                selected_idx = ui.left_panel.selected_index
                if ui.load_disk_health(selected_idx):
                    ui._update_left_panel()
                    needs_redraw = True
        elif key == ord('t') or key == ord('T'):
            # Start short self-test for selected disk
            if ui.active_panel == "left":
                selected_idx = ui.left_panel.selected_index
                success, message = ui.start_short_test(selected_idx)
                if success:
                    ui.set_status(message)
                else:
                    ui.set_error(message)
                ui._update_left_panel()
                needs_redraw = True
        elif key == ord('s') or key == ord('S'):
            # Start btrfs scrub for selected partition in right panel
            if ui.active_panel == "right":
                selected_idx = ui.right_panel.selected_index
                success, message = ui.start_btrfs_scrub(selected_idx)
                if success:
                    ui.set_status(message)
                else:
                    ui.set_error(message)
                needs_redraw = True
        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_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

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

        # Small sleep to prevent CPU spinning
        time.sleep(0.1)


@click.command()
@click.option(
    "--refresh", "-r",
    default=10,
    help="Auto-refresh interval in seconds (0 to disable).",
    type=int
)
@click.version_option(version="0.1.0", prog_name="diskmanager")
def main(refresh: int) -> None:
    """
    Midnight Commander-style disk manager.

    Displays disks and partitions in a two-panel interface.
    Navigate with arrow keys, switch panels with Tab, quit with 'q'.
    """
    try:
        # Run the curses UI with refresh interval
        curses.wrapper(lambda stdscr: run_ui(stdscr, refresh))
    except Exception as e:
        click.echo(f"Error: {e}", err=True)
        raise click.Abort()


if __name__ == "__main__":
    main()
