#include <ncurses.h>
#include <unistd.h>
#include <stdio.h>
#include "tamagotchi.h"
#include "ui.h"

int main() {
    // Open a log file for debugging
    FILE *log_file = fopen("streamii.log", "w");
    if (!log_file) {
        perror("Failed to open log file");
        return 1;
    }

    // Log start of the game
    fprintf(log_file, "Streamii game started\n");
    fflush(log_file);

    // Initialize Tamagotchi
    Tamagotchi streamii;
    init_tamagotchi(&streamii);
    fprintf(log_file, "Streamii initialized\n");
    fflush(log_file);

    // Initialize UI
    init_ui();
    fprintf(log_file, "UI initialized\n");
    fflush(log_file);

    // Game loop
    while (streamii.is_alive) {
        // Update Tamagotchi stats
        update_tamagotchi_stats(&streamii);
        fprintf(log_file, "Updated Streamii stats\n");
        fflush(log_file);

        // Clear and redraw screen
        clear();

        // Draw Tamagotchi
        draw_tamagotchi(&streamii);

        // Draw stats
        draw_stats(&streamii);

        // Display menu
        display_menu();

        // Refresh screen
        refresh();

        // Get user input
        int ch = get_user_input();
        fprintf(log_file, "User input received: %d\n", ch);
        fflush(log_file);

        // Handle user input
        switch (ch) {
            case KEY_F(1):  // F1 to feed
                feed_tamagotchi(&streamii);
                fprintf(log_file, "Fed Streamii\n");
                break;
            case KEY_F(2):  // F2 to sleep
                sleep_tamagotchi(&streamii);
                fprintf(log_file, "Made Streamii sleep\n");
                break;
            case KEY_F(3):  // F3 to play
                play_with_tamagotchi(&streamii);
                fprintf(log_file, "Played with Streamii\n");
                break;
            case KEY_F(4):  // F4 to clean
                clean_tamagotchi(&streamii);
                fprintf(log_file, "Cleaned Streamii\n");
                break;
            case 'q':       // Q to quit
            case 'Q':
                streamii.is_alive = 0;
                fprintf(log_file, "User quit the game\n");
                break;
        }

        // Small delay to control game speed
        usleep(200000);  // 200ms
    }

    // Show game over screen
    show_game_over();
    fprintf(log_file, "Game over\n");

    // Cleanup
    cleanup_ui();
    fclose(log_file);

    return 0;
}