from .utils import quiz_data
import random
import colorama
from colorama import Fore

colorama.init(autoreset=True)

def main():
    print("\n-----WELCOME TO DEVANAGARI QUIZ-----\n")
    print("Choose the answer by typing a number from 1 to 4. You can leave the quiz any time by typing exit.")
    print("\n©Tanja Paljakka\nLicense: GNU AGPLv3\nYou can find more info at the README and the LICENSE files." )

    # Shuffle the questions
    questions = list(quiz_data.keys())
    random.shuffle(questions)

    score = 0

    for i, devanagari in enumerate(questions, 1):
        correct_answer = quiz_data[devanagari]

        # Get 3 incorrect options
        all_answers = list(set(quiz_data.values()))
        all_answers.remove(correct_answer)
        wrong_options = random.sample(all_answers, 3)

        # Combine and shuffle
        options = wrong_options + [correct_answer]
        random.shuffle(options)

        # Print the question and options
        print(f"\n Question {i}/{len(questions)}: {devanagari}")

        for j, option in enumerate(options, 1):
           print(f"\n {j}. {option}")

        # Get user input
        user_input = input("Your answer: ").strip().lower()

        # Check for exit first
        if user_input in ("exit"):
            print("Goodbye!")
            print(Fore.YELLOW + f"Your score: {score}/{len(questions)}")
            return

        #Try to convert to int and check if it's valid
        try:
            choice = int(user_input)

            if 1 <= choice <= len(options):

                if options[choice - 1] == correct_answer:
                    print(Fore.GREEN + "Correct!")
                    score += 1
                    print(Fore.YELLOW + f"Your score: {score}")
                else:
                    print(Fore.RED + "Wrong!") 
                    print(f"The correct answer was: {correct_answer}")
            else:
                print(Fore.RED + "Please enter a number between 1 and 4")
                print(f"The correct answer was: {correct_answer}")

        except (ValueError):
            print(f"Invalid input. The correct answer was: {correct_answer}")



    print("Quiz complete!")
    print(Fore.YELLOW + f"Your score: {score}/{len(questions)}")
    print("How was your playing experience? Please send your feedback for the developers: tddappdev@gmail.com, English or Finnish.")

if __name__ == "__main__":
    main()
