import {existsSync, mkdirSync, writeFileSync} from 'fs';
import * as path from 'node:path';
import {resolve, dirname} from 'path';
import {fileURLToPath} from 'url';

const DIR = resolve(dirname(fileURLToPath(import.meta.url)), '../data/icons');

export async function downloadIcon(icon, path) {
	if(!existsSync(DIR)) mkdirSync(dirname(path), {recursive: true});
	const res = await fetch(`https://openweathermap.org/img/wn/${icon}@2x.png`);
	const buf = Buffer.from(await res.arrayBuffer());
	writeFileSync(path, buf);
}

export async function fetchIcon(icon) {
	const iconPath = path.join(DIR, icon + '.png');
	if(!existsSync(DIR) || !existsSync(iconPath))
		await downloadIcon(icon, iconPath);
	return iconPath;
}

export function frostRisk(tempC, dewPointC, humidity) {
	if (tempC > 4) return 'None'
	if (tempC <= 0 && dewPointC <= 0) return 'High'
	if (tempC <= 2 && humidity > 85) return 'Moderate'
	if (tempC <= 4) return 'Low'
	return 'None'
}
