import random
from thefuzz import fuzz
from thefuzz import process
from greetings import greetings
from answers_base import answers_list
from places import places_list
import re
import pyowm
owm = pyowm.OWM("5f51060dd519adbc1b0238502ff0fc22")

def get_weather(place = 'Federal Republic of Nigeria, NG'):
    weather_mgr = owm.weather_manager()
    observation = weather_mgr.weather_at_place(place)
    temperature = observation.weather.temperature("celsius")["temp"]
    humidity = observation.weather.humidity
    wind = observation.weather.wind()
    print(f'Temperatura: {temperature}°C')
    print(f'Wilgotność: {humidity}%')
    print(f'Prędkość wiatru: {wind["speed"]} m/s')

def find_match_token_set_ratio(text):
    match = None
    best_match = 0

    for answer in answers_list:
        similarity = fuzz.token_set_ratio(text.lower(), answer.lower())
        if similarity > best_match:
            best_match = similarity
            match = answer

    return match

def select_answer(text):
    best_match = 0
    template_matching = None
    answers = []

    for answer, list_of_answers in answers_list.items():
        similarity = fuzz.token_set_ratio(text.lower(), answer.lower())
        if similarity > best_match:
            best_match = similarity
            template_matching = answer
            answers = list_of_answers

    return process.extractOne(text, answers)[0] if answers else None

def select_place(text):
    return places_list.get(text, None)

def chatbot():
    random_greeting = random.choice(greetings)
    print(random_greeting)

    while True:
        question = input("Wpisz pytanie> ")
        found_match = find_match_token_set_ratio(question)
        if found_match:
            answer = select_answer(found_match)
            if (answer == "weather"):
                regex = re.compile(r"\b(\w+)\b")
                matches = regex.findall(question)
                last_word = matches[-1].replace("?", "")
                answer2 = select_place(last_word)
                print(answer2)
                if(answer2 != None):
                    get_weather(answer2[0])
                else:
                    print("Nie ma takiej miejscowości w bazie!")
                    print("Domyślna miejscowość [Federal Republic of Nigeria, NG]")
                    get_weather()
            else:
                print(answer)

        else:
            print("Przepraszam, nie rozumiem. Czy możesz powtórzyć?")

        if question.lower() in ["do widzenia", "exit", "wyjscie", "koniec"]:
            print("Miło było z Tobą porozmawiać. Do zobaczenia!")
            break


if __name__ == "__main__":
    chatbot()



