# ~/.config/kitty/choose_tab.py
from kitty.boss import get_boss
from kittens.tui.handler import Handler
from kittens.tui.loop import Loop


class TabPicker(Handler):
    def __init__(self):
        super().__init__()
        boss = get_boss()
        win = boss.active_window
        self.osw = win.os_window if win else None
        self.tabs = list(self.osw.tabs) if self.osw else []
        self.index = 0

    def draw(self, screen):
        screen.clear()
        if not self.tabs:
            screen.write_line("No tabs. Esc to exit.")
        else:
            screen.write_line("Choose a tab (↑/↓ Enter Esc)")
            for i, t in enumerate(self.tabs):
                mark = "●" if t is self.osw.active_tab else " "
                sel = ">" if i == self.index else " "
                title = t.title or f"Tab {i+1}"
                screen.write_line(f"{sel} {mark} {title}")
        screen.refresh()

    def on_key(self, event):
        if not self.tabs:
            if event.key in ("escape", "enter"):
                self.quit_loop()
            return
        k = event.key
        if k in ("up", "k"):
            self.index = (self.index - 1) % len(self.tabs)
        elif k in ("down", "j"):
            self.index = (self.index + 1) % len(self.tabs)
        elif k == "enter":
            self.osw.set_active_tab(self.tabs[self.index])
            self.quit_loop()
        elif k == "escape":
            self.quit_loop()
        self.refresh()


def main(args):
    # Correct signature for older Kitty: pass the class name and a title string
    Loop(TabPicker, "choose_tab").run()


def handle_result(args, answer, target_window_id, boss):
    pass

