#include "lexer.h"
#include "parser.h"
#include "type_checker.h"
#include "codegen.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

void test_lexer(int argc, char** argv) {
    struct token token;
    for (int i = 1; i < argc; i++) {
        lexer_load(argv[i]);
        while (lexer_pop(&token)) {
            printf("[%s]: ", argv[i]);
            switch (token.type) {
                case TK_IDENT:
                    printf("got identifier: %s\n", token.data.ident);
                    free(token.data.ident);
                    break;
                case TK_STR_LIT:
                    printf("got string: %s\n", token.data.str_lit);
                    free(token.data.str_lit);
                    break;
                case TK_INT_LIT:
                    printf("got int: %lld\n", token.data.int_lit);
                    break;
                case TK_FLOAT_LIT:
                    printf("got float: %lf\n", token.data.float_lit);
                    break;
                case TK_CHAR_LIT:
                    printf("got char: %c\n", token.data.char_lit);
                    break;
                default:
                    printf("got simple token: %d\n", token.type);
            }
        }
        lexer_close();
    }
}

void test_parser(int argc, char** argv) {
    for (int i = 1; i < argc; i++) {
        struct ast ast;
        parse(argv[i], &ast);
        type_check(&ast);

        unsigned int fn_sz = strlen(argv[i]);
        char asm_file[fn_sz + 1];
        strcpy(asm_file, argv[i]);
        asm_file[fn_sz - 1] = 's';
        asm_file[fn_sz] = 0;

        emit_code(&ast, asm_file);
        ast_destroy(&ast);

        char obj_file[fn_sz + 1];
        strcpy(obj_file, argv[i]);
        obj_file[fn_sz - 1] = 'o';
        obj_file[fn_sz] = 0;

        char cmd_buffer[2*fn_sz + 20];
        snprintf(
            cmd_buffer,
            sizeof(cmd_buffer),
            "nasm -f elf64 %s -o %s",
            asm_file,
            obj_file);
        int status = system(cmd_buffer);
        if (status != 0) exit(status);
    }
}

int main(int argc, char** argv) {
    if (argc < 2) {
        fprintf(stderr, "ccc: no input files\n");
        return 1;
    }

    test_parser(argc, argv);
}
