import handy_http_transport;
import slf4d;
import slf4d.default_provider;

import api_mapping;

struct AppConfig {
	ushort port;
	string webOrigin;
	string logLevel;
}

void main() {
	const AppConfig config = readConfig();
	Level logLevel = Levels.INFO;
	if (config.logLevel == "TRACE") {
		logLevel = Levels.TRACE;
	} else if (config.logLevel == "DEBUG") {
		logLevel = Levels.DEBUG;
	} else if (config.logLevel == "WARN") {
		logLevel = Levels.WARN;
	} else if (config.logLevel == "ERROR") {
		logLevel = Levels.ERROR;
	}
	auto provider = new DefaultProvider(logLevel);
    configureLoggingProvider(provider);
	infoF!"Loaded app config: port = %d, webOrigin = %s"(config.port, config.webOrigin);

	Http1TransportConfig transportConfig = defaultConfig();
	transportConfig.port = config.port;
	HttpTransport transport = new TaskPoolHttp1Transport(mapApiHandlers(config.webOrigin), transportConfig);
	transport.start();
}

AppConfig readConfig() {
	import std.file : exists, readText;
	import std.json;
	import std.conv : to;

	AppConfig defaultConfig = AppConfig(
		8080,
		"http://localhost:5173",
		"INFO"
	);
	// Local dev environment if no config is given.
	if (!exists("finnow-api-config.json")) {
		return defaultConfig;
	}
	JSONValue obj = parseJSON(readText("finnow-api-config.json"));
	if ("port" in obj.object) {
		defaultConfig.port = obj.object["port"].integer.to!ushort;
	}
	if ("webOrigin" in obj.object) {
		defaultConfig.webOrigin = obj.object["webOrigin"].str;
	}
	if ("logLevel" in obj.object) {
		defaultConfig.logLevel = obj.object["logLevel"].str;
	}
	return defaultConfig;
}
