import { lastRun } from "https://esm.town/v/logan/lastRun";
import { fetch } from "https://esm.town/v/std/fetch";
import { set } from "https://esm.town/v/std/set?v=11";
import process from "node:process";
export async function emailMeWhenBadAirQuality({ lat, long }: {
lat: number;
long: number;
}) {
const now = new Date();
const apiKey = process.env.WEATHER_BIT_API_KEY;
if (!apiKey) {
throw new Error("Must define WEATHER_BIT_API_KEY in secrets");
}
const res = await fetch(
`https://api.weatherbit.io/v2.0/current/airquality?lat=${lat}&lon=${long}&key=${apiKey}`,
);
const jsonObj = await res.json();
const airQualityNow: number = jsonObj.data[0]?.aqi || 0;
let level = 0;
if (airQualityNow > 50) {
level = 1;
}
if (airQualityNow > 100) {
level = 2;
}
const emailedInLastDay = (new Date(lastRun.date)).getUTCDate() === now.getUTCDate();
if (!emailedInLastDay && (level === 1 || level === 2)) {
console.email(`The air quality is now at ${airQualityNow}.`);
await set("lastRun", {
level,
date: now.toISOString(),
});
return jsonObj;
}
const increasingToBad = lastRun.level !== 3 && level === 3;
if (increasingToBad) {
console.email(`The air quality is now at ${airQualityNow}.`);
await set("lastRun", {
level,
date: now.toISOString(),
});
return jsonObj;
}
return jsonObj;
}