/** Adelaide sun position. Astronomical altitude and azimuth only — not energy yield. */

export const ADELAIDE = { name: "Adelaide", lat: -34.9285, lon: 138.6007 };

const rad = (deg: number) => (deg * Math.PI) / 180;
const deg = (value: number) => (value * 180) / Math.PI;

function firstSunday(year: number, monthIndex: number) {
  const weekday = new Date(Date.UTC(year, monthIndex, 1)).getUTCDay();
  return 1 + (weekday === 0 ? 0 : 7 - weekday);
}

/** Australian Central Daylight Time is used from the first Sunday in October until the first Sunday in April. */
export function adelaideOffsetHours(year: number, month: number, day: number) {
  const october = firstSunday(year, 9);
  const april = firstSunday(year, 3);
  const afterStart = month > 10 || (month === 10 && day >= october);
  const beforeEnd = month < 4 || (month === 4 && day < april);
  return afterStart || beforeEnd ? 10.5 : 9.5;
}

export function sunPosition(year: number, month: number, day: number, minutes: number) {
  const start = Date.UTC(year, 0, 0);
  const now = Date.UTC(year, month - 1, day);
  const n = Math.round((now - start) / 86400000);
  const decl = rad(23.45 * Math.sin(rad((360 / 365) * (n - 81))));
  const b = rad((360 / 365) * (n - 81));
  const eot = 9.87 * Math.sin(2 * b) - 7.53 * Math.cos(b) - 1.5 * Math.sin(b);
  const offset = adelaideOffsetHours(year, month, day);
  const meridian = 15 * offset;
  const solarMinutes = minutes + eot + 4 * (ADELAIDE.lon - meridian);
  const hourAngle = rad((solarMinutes / 60 - 12) * 15);
  const lat = rad(ADELAIDE.lat);
  const altitude = Math.asin(Math.sin(lat) * Math.sin(decl) + Math.cos(lat) * Math.cos(decl) * Math.cos(hourAngle));
  let azimuth = Math.acos(
    Math.min(1, Math.max(-1, (Math.sin(decl) * Math.cos(lat) - Math.cos(decl) * Math.sin(lat) * Math.cos(hourAngle)) / Math.cos(altitude))),
  );
  if (hourAngle > 0) azimuth = Math.PI * 2 - azimuth;
  return {
    altitude,
    azimuth,
    altitudeDeg: Math.round(deg(altitude)),
    azimuthDeg: Math.round(deg(azimuth)),
    up: altitude > 0,
  };
}

/** Unit vector: x east, y up, z north. */
export function sunVector(year: number, month: number, day: number, minutes: number) {
  const { altitude, azimuth, up } = sunPosition(year, month, day, minutes);
  const east = Math.cos(altitude) * Math.sin(azimuth);
  const north = Math.cos(altitude) * Math.cos(azimuth);
  return { x: east, y: Math.sin(altitude), z: north, up };
}

export function parseDate(value: string) {
  const [year, month, day] = value.split("-").map(Number);
  return { year, month, day };
}

export function altitudeSeries(date: string) {
  const { year, month, day } = parseDate(date);
  return Array.from({ length: 15 }, (_, index) => {
    const hour = 5 + index;
    return { hour, altitude: Math.max(0, sunPosition(year, month, day, hour * 60).altitudeDeg) };
  });
}
