#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

__asm__(".globl enchant_rdi\nenchant_rdi:\n\tpop %rdi\n\tret");

#define MAX_ENCHANTS 8

typedef struct {
    char name[24];
    int  level;
    int  pad;
} Enchant;

Enchant book[MAX_ENCHANTS];
int     num_enchants = 0;

void setup(void) {
    setvbuf(stdin,  NULL, _IONBF, 0);
    setvbuf(stdout, NULL, _IONBF, 0);
    setvbuf(stderr, NULL, _IONBF, 0);
}

static void banner(void) {
    puts("");
    puts("  +----------------------------------------------------+");
    puts("  |      Steve's Enchantment Table  [NX Edition]      |");
    puts("  |  [Lapis][XP][Bookshelf][Anvil][Grindstone][Tome]  |");
    puts("  |                                                    |");
    puts("  |      \"Knowledge is just power you haven't         |");
    puts("  |           enchanted yet.\" -- Steve                 |");
    puts("  +----------------------------------------------------+");
    puts("");
}

static void add_enchant(void) {
    if (num_enchants >= MAX_ENCHANTS) {
        puts("Enchantment book is full!");
        return;
    }
    Enchant *e = &book[num_enchants];
    printf("Enchantment name: ");
    read(0, e->name, 23);
    e->name[strcspn(e->name, "\n")] = 0;
    printf("Level (1-5): ");
    char buf[8];
    read(0, buf, 7);
    e->level = atoi(buf);
    num_enchants++;
    puts("Enchantment added to book!");
}

static void show_enchants(void) {
    puts("=== Enchantment Book ===");
    for (int i = 0; i < num_enchants; i++) {
        printf("[%d] %s  (Level %d)\n", i, book[i].name, book[i].level);
    }
    puts("========================");
}

static void enchant_item(void) {
    char idx_buf[8];
    printf("Enchantment index: ");
    read(0, idx_buf, 7);
    int idx = atoi(idx_buf);

    if (idx < 0 || idx >= num_enchants) {
        puts("No such enchantment!");
        return;
    }

    printf("Applying %s (Lv.%d)...\n", book[idx].name, book[idx].level);

    char item[64];
    printf("Item name: ");
    read(0, item, 256);
    printf("Done! Enchanted: %s\n", item);
}

static void menu(void) {
    puts("1. Add Enchantment");
    puts("2. Show Enchantments");
    puts("3. Enchant Item");
    puts("4. Exit");
    printf("> ");
}

int main(void) {
    setup();
    banner();

    char buf[8];
    while (1) {
        menu();
        read(0, buf, 7);
        int choice = atoi(buf);
        switch (choice) {
            case 1: add_enchant();   break;
            case 2: show_enchants(); break;
            case 3: enchant_item();  break;
            case 4: exit(0);
            default: puts("Unknown command!");
        }
    }
    return 0;
}
