# pyright: reportMissingImports=false
# from kitty.window import CwdRequest
import os
from kitty.boss import get_boss
from kitty.fast_data_types import Screen, get_options
from kitty.utils import color_as_int
from kitty.tab_bar import (
    DrawData,
    ExtraData,
    TabBarData,
    as_rgb,
)

opts = get_options()
text_fg = as_rgb(color_as_int(opts.foreground))
icon_fg = as_rgb(color_as_int(opts.color3))
bg = as_rgb(color_as_int(opts.color8))


def draw(screen: Screen, fg: int, bg: int, text: str) -> None:
    screen.cursor.fg = fg
    screen.cursor.bg = bg
    screen.draw(text)


def draw_tab(
    draw_data: DrawData,
    screen: Screen,
    tab: TabBarData,
    before: int,
    max_title_length: int,
    index: int,
    is_last: bool,
    extra_data: ExtraData,
) -> int:
    active_window = get_boss().active_window_for_cwd
    # active_dir = CwdRequest(active_window)
    active_pid = active_window.child.pid

    try:
        with open(f"/tmp/current_venv-{active_pid}", "r") as f:
            env = f.read()
            if env != "":
                env = f"{env}".replace(os.environ.get("HOME", ""), "~")
            else:
                return screen.cursor.x
    except FileNotFoundError:
        print(f"KITTY TAB BAR ERROR: Can't find /tmp/current_venv for {active_pid}")
        return screen.cursor.x

    screen.cursor.x = screen.columns - len(str(env)) - 5

    draw(screen, bg, 0, "")
    draw(screen, 0, bg, " ")
    draw(screen, icon_fg, bg, "")
    draw(screen, text_fg, bg, " " + env)
    draw(screen, 0, bg, " ")

    return screen.cursor.x