#include <stdlib.h>
#include "tamagotchi.h"

// Initialize Tamagotchi with default stats
void init_tamagotchi(Tamagotchi *tama) {
    tama->hunger = 50;
    tama->energy = 100;
    tama->happiness = 75;
    tama->cleanliness = 100;
    tama->state = HAPPY;
    tama->age = 0;
    tama->is_alive = 1;
}

// Feed the Tamagotchi
void feed_tamagotchi(Tamagotchi *tama) {
    if (!tama->is_alive) return;

    tama->hunger += 20;
    if (tama->hunger > MAX_STAT) tama->hunger = MAX_STAT;
    
    tama->cleanliness -= 10;
    if (tama->cleanliness < MIN_STAT) tama->cleanliness = MIN_STAT;
    
    tama->happiness += 5;
    if (tama->happiness > MAX_STAT) tama->happiness = MAX_STAT;
}

// Make Tamagotchi sleep
void sleep_tamagotchi(Tamagotchi *tama) {
    if (!tama->is_alive) return;

    tama->energy += 30;
    if (tama->energy > MAX_STAT) tama->energy = MAX_STAT;
    
    tama->hunger -= 10;
    if (tama->hunger < MIN_STAT) tama->hunger = MIN_STAT;
}

// Play with Tamagotchi
void play_with_tamagotchi(Tamagotchi *tama) {
    if (!tama->is_alive) return;

    tama->happiness += 15;
    if (tama->happiness > MAX_STAT) tama->happiness = MAX_STAT;
    
    tama->energy -= 15;
    tama->hunger -= 10;
    
    if (tama->energy < MIN_STAT) tama->energy = MIN_STAT;
    if (tama->hunger < MIN_STAT) tama->hunger = MIN_STAT;
}

// Clean Tamagotchi
void clean_tamagotchi(Tamagotchi *tama) {
    if (!tama->is_alive) return;

    tama->cleanliness += 30;
    if (tama->cleanliness > MAX_STAT) tama->cleanliness = MAX_STAT;
    
    tama->happiness += 5;
    if (tama->happiness > MAX_STAT) tama->happiness = MAX_STAT;
}

// Update Tamagotchi stats each game cycle
void update_tamagotchi_stats(Tamagotchi *tama) {
    if (!tama->is_alive) return;

    // Gradually decrease stats
    tama->hunger -= 5;
    tama->energy -= 3;
    tama->happiness -= 2;
    tama->cleanliness -= 1;
    tama->age++;

    // Determine state based on stats
    if (tama->hunger <= 20) tama->state = HUNGRY;
    else if (tama->energy <= 20) tama->state = SLEEPY;
    else if (tama->happiness <= 20) tama->state = BORED;
    else tama->state = HAPPY;

    // Check if Tamagotchi dies
    if (tama->hunger <= MIN_STAT || 
        tama->energy <= MIN_STAT || 
        tama->happiness <= MIN_STAT) {
        tama->is_alive = 0;
    }
}

// Get facial expression based on current state
const char* get_tamagotchi_face(Tamagotchi *tama) {
    switch (tama->state) {
        case HAPPY:    return "^w^";
        case HUNGRY:   return "T_T";
        case SLEEPY:   return "~_~";
        case SICK:     return "x_x";
        case BORED:    return "-_-";
        default:       return "o_o";
    }
}