import { ConfigVar, ConfigVarSemanticType } from "./analyze.js";

export function augmentConfigVar(cv: ConfigVar) {
	if (cv.semanticType != null) {
		return;
	}
	const name = cv.name.toLowerCase();
	const value = cv.defaultValue ? String(cv.defaultValue).toLowerCase() : "";
	if (name.includes("postgres") || name.includes("pg")) {
		if (name.includes("url")) cv.semanticType = ConfigVarSemanticType.POSTGRES_URL;
		if (name.includes("password") || name.includes("pass"))
			cv.semanticType = ConfigVarSemanticType.POSTGRES_PASSWORD;
		if (name.includes("user")) cv.semanticType = ConfigVarSemanticType.POSTGRES_USER;
		if (
			name.includes("db_name") ||
			name.includes("database_name") ||
			(name.includes("db") && !name.includes("url"))
		)
			cv.semanticType = ConfigVarSemanticType.POSTGRES_DB;
		if (name.includes("port")) cv.semanticType = ConfigVarSemanticType.POSTGRES_PORT;
		if (name.includes("host")) cv.semanticType = ConfigVarSemanticType.POSTGRES_HOST;
		if (name.includes("sslmode") || name.includes("ssl")) cv.semanticType = ConfigVarSemanticType.POSTGRES_SSL;
	}
	if (name.includes("mongo")) {
		if (name.includes("url") || name.includes("uri")) cv.semanticType = ConfigVarSemanticType.MONGO_URL;
		if (name.includes("password") || name.includes("pass")) cv.semanticType = ConfigVarSemanticType.MONGO_PASSWORD;
		if (name.includes("user")) cv.semanticType = ConfigVarSemanticType.MONGO_USER;
		if (
			name.includes("db_name") ||
			name.includes("database_name") ||
			(name.includes("db") && !name.includes("url"))
		)
			cv.semanticType = ConfigVarSemanticType.MONGO_DB;
		if (name.includes("port")) cv.semanticType = ConfigVarSemanticType.MONGO_PORT;
		if (name.includes("host")) cv.semanticType = ConfigVarSemanticType.MONGO_HOST;
		if (name.includes("ssl")) cv.semanticType = ConfigVarSemanticType.MONGO_SSL;
	}
	if (name.includes("sqlite_path") || value.endsWith(".sqlite") || value.endsWith(".db3") || value.endsWith(".db")) {
		cv.semanticType = ConfigVarSemanticType.SQLITE_PATH;
	}
	if (name.includes("sqlite") && (name.includes("url") || name.includes("uri") || name.includes("path"))) {
		cv.semanticType = ConfigVarSemanticType.SQLITE_PATH;
	}
	if (name.includes("database_url") || name.includes("db_url")) {
		cv.semanticType = ConfigVarSemanticType.DATABASE_URL;
	}
	if (name.includes("path") || name.includes("file_path") || name.includes("dir") || name.includes("directory")) {
		if (
			!name.includes("url") &&
			(value.startsWith("./") || value.startsWith("../") || value.startsWith("/") || /^[a-z]:[\\/]/.test(value))
		) {
			cv.semanticType = ConfigVarSemanticType.FILESYSTEM_PATH;
		}
	}
	if (
		!name.includes("url") &&
		(value.startsWith("./") || value.startsWith("../") || value.startsWith("/") || /^[a-z]:[\\/]/.test(value))
	) {
		cv.semanticType = ConfigVarSemanticType.FILESYSTEM_PATH;
	}
	if (name.includes("port")) {
		cv.semanticType = ConfigVarSemanticType.PORT;
	}
}
