#include "defs.h"

static void parse_options(void)
{
    FILE *f = fopen(OPT_FILE, "r");
    if (!f) return;

    char line[256];
    while (fgets(line, sizeof(line), f)) {
        /* Strip newline */
        char *nl = strchr(line, '\n');
        if (nl) *nl = 0;
        /* Skip comments and blank lines */
        if (line[0] == '#' || line[0] == 0) continue;

        /* Handle ! prefix as negation */
        char *opt = line;
        int negate = 0;
        if (line[0] == '!') {
            negate = 1;
            opt = line + 1;
        }

        if (strcmp(opt, "introduction") == 0) G->opts.introduction = !negate;
        else if (strcmp(opt, "no-introduction") == 0) G->opts.introduction = 0;
        else if (strcmp(opt, "bold-cursor") == 0) G->opts.bold_cursor = !negate;
        else if (strcmp(opt, "blink-cursor") == 0) G->opts.blink_cursor = !negate;
        else if (strcmp(opt, "reverse-cursor") == 0) G->opts.reverse_cursor = !negate;
        else if (strcmp(opt, "bold-bems") == 0) G->opts.bold_bems = !negate;
        else if (strcmp(opt, "bold-objects") == 0) G->opts.bold_objects = !negate;
        else if (strcmp(opt, "bold-installations") == 0) G->opts.bold_installs = !negate;
        else if (strcmp(opt, "reverse-objects") == 0) G->opts.reverse_objects = !negate;
        else if (strcmp(opt, "reverse-installations") == 0) G->opts.reverse_installs = !negate;
        else if (strcmp(opt, "highlight-location") == 0) G->opts.highlight_location = !negate;
        else if (strcmp(opt, "show-unexplored") == 0) G->opts.show_unexplored = !negate;
        else if (strcmp(opt, "log-messages") == 0) G->opts.log_messages = !negate;
        else if (strcmp(opt, "special-fonts") == 0) G->opts.special_fonts = !negate;
        else if (strcmp(opt, "scoreboard") == 0) G->opts.scoreboard = !negate;
        else if (strcmp(opt, "no-bell") == 0) G->opts.no_bell = !negate;
        else if (strcmp(opt, "brief") == 0) G->player.brief_mode = !negate;
        else if (strcmp(opt, "verbose") == 0) G->player.brief_mode = negate;
        else if (strcmp(opt, "auto-take") == 0) G->player.auto_take = !negate;
        else if (strcmp(opt, "statistics") == 0) G->opts.statistics = !negate;
        else if (strcmp(opt, "snapshot-at-death") == 0) G->opts.snapshot_at_death = !negate;
        else if (strcmp(opt, "enable-control-c") == 0) G->opts.enable_ctrl_c = !negate;
        else if (strcmp(opt, "male") == 0) G->player.gender = 0;
        else if (strcmp(opt, "female") == 0) G->player.gender = 1;
        else if (strncmp(opt, "name:", 5) == 0) {
            strncpy(G->player.name, opt + 5, MAX_NAME - 1);
        }
    }
    fclose(f);
}

static void parse_cmdline(int argc, char **argv)
{
    for (int i = 1; i < argc; i++) {
        if (strcmp(argv[i], "intro") == 0) G->opts.introduction = 1;
        else if (strcmp(argv[i], "nointro") == 0) G->opts.introduction = 0;
        else if (strcmp(argv[i], "debug") == 0) G->debug_mode = 1;
        else if (strcmp(argv[i], "rename") == 0) {
            /* Will prompt after init */
        }
    }
}

static void new_game(void)
{
    player_init(&G->player);
    parse_options();

    /* Prompt for character acceptance */
    display_init();

    if (G->opts.introduction) {
        display_intro();
    }

    msg("DoomsDay 2026    Version %d.%d%c    Copyright (c) 1987    All Rights Reserved",
        GAME_VERSION_MAJ, GAME_VERSION_MIN, GAME_VERSION_REV);
#ifdef __VMS
    msg("OpenVMS x86_64 port (c) 2026. Original by Dave Scheifler, Digital Equipment Corporation.");
#else
    msg("Unix port (c) 2026. Original by Dave Scheifler, Digital Equipment Corporation.");
#endif

    for (;;) {
        player_roll_stats(&G->player);
        display_stats();
        display_refresh();

        if (display_prompt_yn("Accept this character (y/n)? "))
            break;
    }

    /* Initialize first level */
    map_init();
    level_t *lev = map_get_level(0);

    /* Place player on first level */
    for (int y = 0; y < MAP_H; y++)
        for (int x = 0; x < MAP_W; x++)
            if (lev->map[y][x].tile == T_FLOOR) {
                G->player.x = x;
                G->player.y = y;
                goto placed;
            }
placed:
    G->player.depth = 0;
    G->player.region = 1;
    G->cur_level = 0;

    /* Initialize pill color mapping */
    for (int i = 0; i < PILL_COUNT; i++)
        G->pill_color_map[i] = i;
    for (int i = PILL_COUNT - 1; i > 0; i--) {
        int j = rng(0, i);
        int tmp = G->pill_color_map[i];
        G->pill_color_map[i] = G->pill_color_map[j];
        G->pill_color_map[j] = tmp;
    }
}

static void game_loop(void)
{
    G->running = 1;

    while (G->running && G->player.alive) {
        level_t *lev = G->levels[G->cur_level];

        /* Update field of view */
        map_update_fov();

        /* Render */
        display_map();
        display_stats();
        if (G->inv_visible)
            display_inventory();
        display_refresh();

        /* Get and process input */
        int prev_x = G->player.x, prev_y = G->player.y;
        int prev_level = G->cur_level;
        input_process();

        if (!G->player.alive || !G->running) break;

        /* Monster turns */
        monsters_move(lev);

        if (!G->player.alive) break;

        /* Check for installation interactions (only on arrival) */
        if (G->player.x != prev_x || G->player.y != prev_y ||
            G->cur_level != prev_level) {
            lev = G->levels[G->cur_level];
            cell_t *c = &lev->map[G->player.y][G->player.x];
            if (c->install_type > 0) {
                switch (c->install_type) {
                case IT_AUTODOC: install_autodoc(); break;
                case IT_TRANSMAT: install_transmat(); break;
                case IT_VENDING_MACHINE: install_vending(); break;
                case IT_BANK: install_bank(); break;
                case IT_LIBRARIAN: install_library(); break;
                case IT_FACTORY_OUTLET: install_factory(); break;
                case IT_RECLAMATION_CENTER: install_reclamation(); break;
                case IT_WATER_FOUNTAIN: install_fountain(); break;
                case IT_SMALL_GENERATOR: install_generator(); break;
                case IT_STARGATE: install_stargate(); break;
                }
            }
        }

        /* Check mission completion */
        if (G->player.mission == MISSION_1_COMPLETE) {
            msg("To be continued ...");
            msg("... to a briefing room.  For it seems that one last mission lies before you,");
            msg("... a mission that is equally vital to the Cause.");
            G->player.mission = MISSION_2_ACTIVE;
        }

        if (G->player.mission == MISSION_2_COMPLETE) {
            msg("... For now there is hope, hope that the tide of battle has finally turned");
            msg("... in favor of the Terran Freedom Forces.");
            G->player.alive = 0; /* End game (victory) */
        }

        if (G->player.mission == MISSION_FAILED) {
            msg("... he confines you to quarters and assigns the task to a more capable agent.");
            G->player.alive = 0;
        }

        /* Alert system ambient messages */
        if (G->player.alert_level >= ALERT_YELLOW && rng_chance(5)) {
            switch (G->player.alert_level) {
            case ALERT_YELLOW:
                msg("*** CONDITION YELLOW ***");
                break;
            case ALERT_ORANGE:
                msg("ATTENTION ALL UNITS!");
                msg("*** CONDITION ORANGE ***");
                break;
            case ALERT_RED:
                msg("ATTENTION ALL UNITS!");
                msg("*** CONDITION RED ***");
                msg("... Search and Destroy ...");
                break;
            case ALERT_VIOLET:
                msg("ATTENTION ATTENTION ATTENTION");
                msg("*** CONDITION VIOLET ***");
                msg("... All Units To StarGate ...");
                break;
            default: break;
            }
        }

        /* Ambient messages */
        if (rng_chance(2)) {
            static const char *ambient[] = {
                "The ground suddenly trembles beneath your feet ...",
                "You have a nasty feeling about this place ...",
                "You briefly hear the hum of powerful machinery in the distance ...",
                "Sounds of metal on stone can be heard below ... or perhaps above ...",
                "You sense something ominous almost happened ...",
            };
            msg("%s", ambient[rng(0, 4)]);
        }
    }

    /* Game over */
    if (!G->player.alive) {
        if (G->opts.scoreboard) {
            const char *cause = "died for inexplicable reasons";
            if (G->player.mission == MISSION_2_COMPLETE)
                cause = "completed Mission #2";
            else if (G->player.mission == MISSION_1_COMPLETE)
                cause = "completed Mission #1";
            else if (G->player.mission == MISSION_FAILED)
                cause = "wimped out";
            save_scoreboard(cause);
        }
        if (G->opts.statistics) {
            long elapsed = time(NULL) - G->player.session_start;
            msg("Session Elapsed Time:    %ldm %lds", elapsed / 60, elapsed % 60);
            msg("Be seeing you ...");
            wgetch(G->win_map);
        }
    }
}

int main(int argc, char **argv)
{
    /* Allocate game state */
    G = calloc(1, sizeof(game_t));
    if (!G) {
        fprintf(stderr, "Failed to allocate game state\n");
        return 1;
    }

    /* Seed RNG */
    G->rng_seed = time(NULL);
    srand((unsigned int)G->rng_seed);

    /* Default options */
    G->opts.introduction = 1;
    G->opts.show_unexplored = 1;
    G->opts.log_messages = 1;
    G->opts.scoreboard = 1;
    G->opts.bold_cursor = 1;
    G->opts.bold_objects = 1;
    G->opts.highlight_location = 1;

    parse_cmdline(argc, argv);

    /* Try to load saved game */
    if (load_game(SAVE_FILE)) {
        display_init();
        msg("(game in progress, restored from %s)", SAVE_FILE);
        msg("Welcome back, %s", G->player.name);
    } else {
        new_game();
    }

    game_loop();

    display_cleanup();

    /* Free levels */
    for (int i = 0; i < MAX_LEVELS; i++)
        free(G->levels[i]);
    free(G);

    return 0;
}
