from time import sleep
import datetime as dt
from datetime import datetime
from openai import OpenAI
import threading

number_map = {
    "0": "o'clock",
    "1": "one",
    "2": "two",
    "3": "three",
    "4": "four",
    "5": "six",
    "6": "six",
    "7": "seven",
    "8": "eight",
    "9": "nine",
    "10": "ten",
    "11": "eleven",
    "12": "twelve",
    "13": "thirteen",
    "14": "fourteen",
    "15": "fifteen",
    "16": "sixteen",
    "17": "seventeen",
    "18": "eighteen",
    "19": "nineteen",
    "20": "twenty",
    "30": "thirty",
    "40": "forty",
    "50": "fifty",
}


class Clock:
    def __init__(self):
        time_prompt = self.serialize_time(datetime.now())
        self.time = self.generate_rhyme(time_prompt)

    def serialize_time_part(self, part):
        part_string = ""
        if part in number_map:
            part_string += number_map[part]
        else:
            tens_str = number_map[f"{part[0]}0"]
            ones_str = number_map[part[1]]
            part_string += f"{tens_str}-{ones_str}"
        return part_string

    def serialize_time(self, time):
        hour = str(time.hour)
        if time.hour > 12:
            hour = str(time.hour - 12)
        elif time.hour == 0:
            hour = "12"
        hour = self.serialize_time_part(hour)
        minute = str(time.minute)
        if time.minute < 10:
            minute = f"o'{self.serialize_time_part(minute)}"
        else:
            minute = self.serialize_time_part(minute)
        time_string = f"{hour} {minute}"
        return time_string

    def generate_rhyme(self, time):
        client = OpenAI()
        response = client.chat.completions.create(
            model="gpt-4",
            messages=[
                {
                    "role": "user",
                    "content": f"Finish this sentence about the time with a rhyme. It's {time}, ",
                }
            ],
        )
        rhyme = response.choices[0].message.content
        return f"It's {time}, {rhyme}"

    def start_update_loop(self):
        thread = threading.Thread(target=self.update_loop)
        thread.daemon = True
        thread.start()

    def update_loop(self):
        while True:
            now = datetime.now()
            then = datetime(now.year, now.month, now.day, now.hour, now.minute + 1, 0)
            seconds_until = (then - now).total_seconds()
            sleep(seconds_until)
            time_prompt = self.serialize_time(datetime.now())
            self.time = self.generate_rhyme(time_prompt)
