#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <inttypes.h>
#include <ctype.h>
#include <limits.h>
#include <errno.h>

#include "common.h"
#include "strn.h"

#ifndef _WIN32
#include <unistd.h>
#endif

#define _XOPEN_SOURCE
#include <time.h>

#include "vstr.h"
#include <account.h>
#include <book.h>

#define BUFFER_SIZE 256

#define warning(STR) \
	fprintf(stdout, "\033[31m"STR"\033[0m");

#define warningf(STR,...) \
	fprintf(stdout, "\033[31m"STR"\033[0m", __VA_ARGS__);

vstr_t tags[100] = { 0 };

size_t tags_size = 0;

/*
 * char* tags = { "Expenses:Auto:Gas", "Liabilities:MasterCard",
 * "Assets:Credit" };
 */

/**
 *
 read the file | parse for newlines
 2023/10/24 - 5, fptr + 0, fptr + 6, fptr + 9
 Entry* entry = get_entry("2023/10/24");

 skip \n
 read until date, and read until from

 **/

// commodity max size 256
// commodity name max size 4
char commodity_list[256][8];

map_tree_t *rootp = NULL;


// store numbers in the least denom
// 1.50$ == 150
// 2$ == 200
// 2.23$ == 200

typedef struct {
	vstr_t *denom;
	size_t quantity;
	int8_t decimal;
} LedgerValue;

typedef struct {
	vstr_t *reg;
	LedgerValue val;
} LedgerRecord;

typedef struct {
	time_t date;		// the date associated with the entry
	vstr_t comment;		// comment associated with the entry
	LedgerRecord **records;
} LedgerEntry;

time_t
ledger_timestamp_from_ledger_date(char *date_str)
{
	// converts string 'YYYY-MM-DD' to unix timestamp
	// date_str should be exactly 10 characters
	// printf("%.*s\n", 4, date_str);
	struct tm tm = { 0 };
	tm.tm_year = natoi(date_str, 4) - 1900;
	tm.tm_mon = natoi(date_str + 5, 2) - 1;
	tm.tm_mday = natoi(date_str + 8, 2);
	// warning("tm_year %d, tm_mon: %d, tm_mday: %d", natoi(date_str, 4),
	// tm.tm_mon, tm.tm_mday);
	return mktime(&tm);
}

const char *states_str[] = {
	"DATE",
	"COMMENT",
	"ENTRY START",
	"ENTRY SPACE",
	"ENTRY WHO",
	"ENTRY AMOUNT",
	"ENTRY DENOM",
	"ENTRY END",
};

typedef enum {
	DATE,
	COMMENT,
	ENTRY_START, // entry starts after a comment
	ENTRY_SPACE,
	ENTRY_WHO,
	ENTRY_AMOUNT,
	ENTRY_DENOM ,
	ENTRY_END, // finish up entry if encountering any \n\n or \n text_len == i or text_len == i, otherwise set state to ENTRY_SPACE
	POSTING_END,
} LedgerParseStates;


void
ledger_parse_data(char *text, size_t text_len)
{
	char *denom_list[256];
	memset(denom_list, 0, 256);
	char* denomptr = NULL;
	setvbuf(stdout, NULL, _IONBF, 0);

	LedgerParseStates state = DATE;
	size_t line_no = 1;
	size_t current_column = 1;
	time_t t = time(NULL);
	size_t i = 0;
	// TODO it may be possible to push these to the tree itself, explore the possibility
	// these act as temporary register until we push back the entry to a tree
	time_t hold_date;
	vstr_t hold_comment = { 0 };
	vstr_t hold_register = { 0 };
	long hold_amount = LONG_MAX;
	char hold_sign = 0;
	size_t hold_denom_id = { 0 };
	short n_count = 0;
	char hold_fquantity = 0;

	hold_amount = LONG_MAX;

	setvbuf(stdout, NULL, _IONBF, 0);
	// TODO it may be possible to push these to the tree itself, explore the possibility
	// these act as temporary register until we push back the entry to a tree

	while (i < text_len) {
		char c = text[i];
		/* \n identifies an entry done in ledger */
		switch (c) {
			case '\n':
			case '\r':
				line_no++;
				n_count++;
				switch (state) {
					// after parsing the amount seq, we set the state to ENTRY_WHO
					case ENTRY_WHO:
					case ENTRY_END:
						hold_sign = 0;
						hold_amount = LONG_MAX;
						hold_denom_id = 0;
						// if entry_count <= 1 throw error
						if (text[i - 1] == '\n') {
							state = DATE;
							// TODO push the entries to stack or somethin
							warning("\n==\n");
							// state = POSTING_END;
							break;
						}
						state = ENTRY_WHO;
						warning(",");
						break;
					case COMMENT:
						state = ENTRY_START;
						break;
					case ENTRY_DENOM:
						//warningf("%s", "denom not found, setting state WHO");
						state = ENTRY_WHO;
						break;
					case ENTRY_AMOUNT:
						goto ledger_parse_error_handle;
						break;
				}
				i++;
				continue;
			case ' ':
			case '\t':
				n_count = 0;
				i++;
				continue;
				break;
		}
		n_count = 0;
		// next state
		switch (state) {
			case DATE:
				if (isdigit(c)) {
					// try to parse a date
					time_t tn = ledger_timestamp_from_ledger_date(text + i);
					warningf("%.*s: %ld	", 10, text + i, (long)tn);
					// date is expected to have the form DD/MM/YYYY (10)
					i += 10;
					if (tn == (time_t) - 1) goto ledger_parse_error_handle;
					state = COMMENT;
				}
				break;
			case COMMENT:
				if (isalnum(c)) {
					// we hit alphanumerical after whitespace
					vstr_t comment = {
						.str = text + i,
						.len = 0
					};
					while (i < text_len && *(text + i) != '\n') {
						i++;
						comment.len++;
					}
					warningf("Comment: %.*s", comment.len,
							comment.str);
					state = ENTRY_START;
				}
				break;
			case ENTRY_START:
			case ENTRY_WHO:
				{
					// add this to register
					size_t who_len = i;
					vstr_t who = {
						.str = text + i,
						.len = 0
					};
					while (i < text_len) {
						switch (text[i]) {
							case '\n':
							case '\r':
								goto ledger_who_parsed;
								break;
							case '\t':
							case ' ':
								goto ledger_who_parsed;
								break;
							default:
								i++;
								break;
						}
					}
ledger_who_parsed:
					who_len = i - who_len;
					account_add(&rootp, who.str, who_len);
					warningf("\n@%d Who=%.*s", i, who_len, who);
					state = ENTRY_DENOM;
					/* TODO add to tags here */
				}
				break;
			case ENTRY_DENOM: {
				char _c;
				if (hold_denom_id) {
					warning("Denom already parsed\n");
					goto ledger_parse_error_handle;
				}
				char *denom = text + i;
				size_t denom_len = 0;

				if (*denom == '-') {
					if (hold_sign) goto ledger_parse_error_handle;
					hold_sign = 1;
					i++;
					state = ENTRY_DENOM;
					break;
				}

				warningf(" @%d D", i + 1);

				while (i < text_len &&
						( isalpha(*(text + i))
				/* TODO Search denomlist instead of just checking '$' */
						 || *(text + i) == '$')) i++;
				denom_len = (text + i) - denom;
				/* FIXME Use proper id */
				hold_denom_id = *denom;//get_denom_id(denom, denom_len);
				// hold_denom_len = denom_len;
				state = hold_amount == LONG_MAX? ENTRY_AMOUNT : ENTRY_END;
				warningf("#%d(%.*s)", denom_len, denom_len, denom);
				break;
			}
			case ENTRY_AMOUNT: {
				char _c;
				if (hold_amount != LONG_MAX) {
					warning("Amount already parsed\n");
					goto ledger_parse_error_handle;
				}

				char *amount = text + i;
				size_t amount_len = 0;

				char *eptr = NULL;
				char *efptr = NULL;

				if (*amount == '-') {
					if (hold_sign) goto ledger_parse_error_handle;
					hold_sign = 1;
					i++;
					state = ENTRY_AMOUNT;
					break;
				}

				warningf(" @%d A", i + 1);

				hold_amount = strtol(amount, &eptr, 10);

				if (errno == ERANGE) {
					perror("FATAL: Big ints are not supported at the moment");
					exit(-1);
				}
				if (errno) {
					perror("Some unknown error occured while parsing quantity");
					exit(-1);
				}

				amount_len = eptr - amount;

				if (*eptr == ',') *eptr = '.';
				if (amount_len && *eptr == '.') {
					float temp = strtof(eptr, &efptr);
					if (efptr == eptr) {
						/*
						TODO Check if '.' should end a transaction
						TODO Handle @
						*/
						printf("Searching for decimal value got '%c'\n", *efptr);
						exit(-1);
					}

					if (efptr - eptr > 3) {
						warning("FATAL: Only 2 decimal places are supported at the moment\n");
						exit(-1);
					}
					hold_fquantity = (char) (temp * 100);
					eptr = efptr;
				}

				amount_len = eptr - amount;
				i += amount_len;

				/* number parse failed */
				if (eptr == amount) {
					if (hold_denom_id) goto ledger_parse_error_handle;
					state = ENTRY_DENOM;
					break;
				}

				state = hold_denom_id ? ENTRY_END : ENTRY_DENOM;
				warningf("#%d(%.*s)", amount_len, amount_len, amount);
				}
				break;
			default:
				goto ledger_parse_error_handle;
		}
	}
	warning("read complete\n");
	return;
ledger_parse_error_handle:
	warningf("\nParse failed @%d line:%ld, Expected %s, got '%c'\n",
			i, line_no, states_str[state], text[i]);
}

Entry**
ledger_read_file(const char* filename, time_t date_start, time_t date_end) {
	Entity me = {"Account:Income"};
	// list population, read from
	FILE* file = fopen(filename, "r");
	if (file == NULL) {
		printf("Failed to open file %s\n", filename);
	}
	Entry** new_list = (Entry**)malloc(sizeof(Entry*) * 12);
	for(int i = 0; i < 12; i++) {
		Entry* entry = (Entry*)malloc(sizeof(Entry));
		new_list[i] = entry;
		entry->from = &me;
		entry->to = (Entity*)malloc(sizeof(Entity));
		entry->to->name = (char*)malloc(sizeof(char*) * 20);
		strncpy(entry->to->name, "Man", 3);
	}
	return new_list;
}

void
*module_main(char *data, size_t data_len)
{
	// printf("%s\n", data);
	warning("\n=======| Startality |=======\n");
	ledger_parse_data(data, data_len);
	warning("\n========| Fatality |========\n");
	return NULL;
}

