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

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

export const WMO = {
	0: {label: 'Clear Sky', icon: '01d'},
	1: {label: 'Mainly Clear', icon: '01d'},
	2: {label: 'Partly Cloudy', icon: '02d'},
	3: {label: 'Overcast', icon: '04d'},
	45: {label: 'Fog', icon: '50d'},
	48: {label: 'Icy Fog', icon: '50d'},
	51: {label: 'Light Drizzle', icon: '09d'},
	53: {label: 'Drizzle', icon: '09d'},
	55: {label: 'Heavy Drizzle', icon: '09d'},
	61: {label: 'Light Rain', icon: '10d'},
	63: {label: 'Rain', icon: '10d'},
	65: {label: 'Heavy Rain', icon: '10d'},
	71: {label: 'Light Snow', icon: '13d'},
	73: {label: 'Snow', icon: '13d'},
	75: {label: 'Heavy Snow', icon: '13d'},
	77: {label: 'Snow Grains', icon: '13d'},
	80: {label: 'Light Showers', icon: '09d'},
	81: {label: 'Showers', icon: '09d'},
	82: {label: 'Heavy Showers', icon: '09d'},
	85: {label: 'Snow Showers', icon: '13d'},
	86: {label: 'Heavy Snow Showers', icon: '13d'},
	95: {label: 'Thunderstorm', icon: '11d'},
	96: {label: 'Thunderstorm w/ Hail', icon: '11d'},
	99: {label: 'Thunderstorm w/ Hail', icon: '11d'},
};

export async function downloadIcons() {
	if(!existsSync(DIR)) mkdirSync(DIR, {recursive: true});
	const icons = new Set(Object.values(WMO).map(w => [w.icon, w.icon.replace('d', 'n')]).flat());
	await Promise.all([...icons].map(async icon => {
		const path = resolve(DIR, `${icon}.png`);
		if(existsSync(path)) return;
		const res = await fetch(`https://openweathermap.org/img/wn/${icon}@2x.png`);
		const buf = Buffer.from(await res.arrayBuffer());
		writeFileSync(path, buf);
		console.log(`  📥 Downloaded icon: ${icon}.png`);
	}));
	console.log('✅ Weather icons ready');
}

export function getWeatherCondition(data) {
	// Determine primary condition
	if(data.lightning_rate > 0 && data.raining === 'True') {
		return {label: 'Thunderstorm', code: 211, icon: '11d'};
	}

	if(data.raining === 'True') {
		if(data.precipitation > 7.6) return {label: 'Heavy Rain', code: 502, icon: '10d'};
		if(data.precipitation > 2.5) return {label: 'Moderate Rain', code: 501, icon: '10d'};
		return {label: 'Light Rain', code: 500, icon: '09d'};
	}

	if(data.visibility < 10) {
		return {label: 'Mist', code: 701, icon: '50d'};
	}

	const dayNight = data.daytime ? 'd' : 'n';
	if(data.clouds > 85) return {label: 'Overcast Clouds', code: 804, icon: `04${dayNight}`};
	if(data.clouds > 50) return {label: 'Broken Clouds', code: 803, icon: `04${dayNight}`};
	if(data.clouds > 25) return {label: 'Scattered Clouds', code: 802, icon: `03${dayNight}`};
	if(data.clouds > 10) return {label: 'Few Clouds', code: 801, icon: `02${dayNight}`};

	return {label: 'Clear Sky', code: 800, icon: `01${dayNight}`};
}
