import re
from datetime import datetime

from textual.widgets import Static
from textual.reactive import reactive
from rich.text import Text

from hibiscus.constants import BABY_BLUE, START_DATE, COLOR_POOL


def colorize_sonnet_line(text: str, line_index: int) -> Text:
    result = Text()
    segments = re.split(r'(\s+)', text)
    word_idx = 0
    for segment in segments:
        if segment.strip() == "":
            result.append(segment)
        else:
            color = COLOR_POOL[(line_index * 3 + word_idx) % len(COLOR_POOL)]
            result.append(segment, style=f"italic {color}")
            word_idx += 1
    return result


class CounterWidget(Static):
    value = reactive(0)
    live = reactive(False)

    def on_mount(self) -> None:
        self.set_interval(1.0, self._tick)

    def _tick(self) -> None:
        if self.live:
            now = datetime.now()
            self.value = int((now - START_DATE).total_seconds())

    def watch_value(self, val: int) -> None:
        formatted = f"{val:,}"
        t = Text(formatted, style=f"bold {BABY_BLUE}")
        self.update(t)
