
using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using OpenAI_API.Completions;
using OpenAI_API;

namespace MovieSearchApp
{

    public partial class MainWindow : Window
    {
        private const string ConnectionString = "Data Source=C:\\ProgramData\\Team MediaPortal\\MP2-Server\\Database\\Datastore.s3db;Version=3;";
        private const string OpenAIApiKey = "...";

        private List<string> movieList; // List to store movie titles
        //private string movieListText; // Variable to hold the concatenated movie titles


        public MainWindow()
        {
            InitializeComponent();
            movieList = new List<string>();
            PopulateMovieList();
            DisplayMovieList(movieListBox, movieList);
        }

        private void PopulateMovieList()
        {
            using (SQLiteConnection connection = new SQLiteConnection(ConnectionString))
            {
                connection.Open();

                //string sql = "SELECT MOVIENAME FROM M_MOVIEITEM;";
                //using (SQLiteCommand command = new SQLiteCommand(sql, connection))
                //using (SQLiteDataReader reader = command.ExecuteReader())
                //{
                //    while (reader.Read())
                //    {
                //        string movieTitle = reader["MOVIENAME"].ToString();
                //        movieListBox.Items.Add(movieTitle);
                //    }
                string sql = "SELECT MOVIENAME FROM M_MOVIEITEM LIMIT 300;"; // Limit to the first 300 movies
                using (SQLiteCommand command = new SQLiteCommand(sql, connection))
                using (SQLiteDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        string movieTitle = reader["MOVIENAME"].ToString();
                        movieList.Add(movieTitle);
                    }
                }
            }
        }


        private async void SearchButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string searchQuery = searchTextBox.Text.Trim();

                if (string.IsNullOrEmpty(searchQuery))
                {
                    MessageBox.Show("Please enter a search query.");
                    return;
                }

                // Use ChatGPT to filter movies based on the search query
                List<string> filteredMovies = await FilterMoviesWithGPT(searchQuery);

                // Display the filtered movies
                DisplayMovieList(resultListBox, filteredMovies);

                // Filter the items in resultListBox based on the items present in movieListBox
                FilterResultListBox();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"An error occurred: {ex.Message}");
            }
        }

        private void FilterResultListBox()
        {
            // Filter items in resultListBox based on items present in movieListBox
            List<string> filteredResult = new List<string>();
            foreach (var item in resultListBox.Items)
            {
                if (movieListBox.Items.Contains(item))
                {
                    filteredResult.Add(item.ToString());
                }
            }

            // Display the filtered items in resultListBox
            DisplayMovieList(resultListBox, filteredResult);
        }

        private async Task<List<string>> FilterMoviesWithGPT(string searchQuery)
        {
            // Use ChatGPT to determine if each movie fits the search query
            string generatedText = await GenerateResponseWithGPT(searchQuery, movieList);
            //MessageBox.Show($"Filtered Movies: {generatedText}");
            // Split the generated text into a list of matches
            List<string> filteredMovies = new List<string>(generatedText.Split(';'));

            return filteredMovies;
            
        }

        private async Task<string> GenerateResponseWithGPT(string searchQuery, List<string> movieList)
        {
            APIAuthentication aPIAuthentication = new APIAuthentication(OpenAIApiKey);
            OpenAIAPI openAiApi = new OpenAIAPI(aPIAuthentication);
            string movieListText = string.Join(";", movieList);
            try
            {
                string prompt = $"Filter for only movies from <{movieListText}> if following is true for the movie: {searchQuery}. Use a simikolon as separator and do not write any summary comments. No result means the output is simply empty";
                string model = "text-davinci-003";
                int maxTokens = 500;

                var completionRequest = new CompletionRequest
                {
                    Prompt = prompt,
                    Model = model,
                    MaxTokens = maxTokens
                };

                var completionResult = await openAiApi.Completions.CreateCompletionAsync(completionRequest);
                var generatedText = completionResult.Completions[0].Text; //completionResult.Choices[0].Text.Trim();
                MessageBox.Show($"Filtered Movies: {completionResult}");
                return generatedText;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"An error occurred: {ex.Message}");
                return "error";
            }
        }
        private void DisplayMovieList(ListBox listBox, List<string> movies)
        {
            listBox.ItemsSource = movies;
        }
    }
}