/**
 * src/arabic/hijri.ts
 * أدوات التقويم الهجري — Hijri calendar, prayer times, Saudi business utilities
 */
import { z } from 'zod';
import { createChildLogger } from '../utils/logger.js';
const log = createChildLogger('arabic:hijri');
const HIJRI_MONTHS_AR = [
    'محرم', 'صفر', 'ربيع الأول', 'ربيع الثاني',
    'جمادى الأولى', 'جمادى الآخرة', 'رجب', 'شعبان',
    'رمضان', 'شوال', 'ذو القعدة', 'ذو الحجة',
];
const HIJRI_MONTHS_EN = [
    'Muharram', 'Safar', 'Rabi al-Awwal', 'Rabi al-Thani',
    'Jumada al-Ula', 'Jumada al-Akhirah', 'Rajab', 'Shaban',
    'Ramadan', 'Shawwal', 'Dhul Qadah', 'Dhul Hijjah',
];
// ─── Gregorian to Hijri Conversion ──────────────────────────────────
// Using the Umm al-Qura algorithm (tabular approximation)
export function toHijri(date = new Date()) {
    const jd = gregorianToJD(date.getFullYear(), date.getMonth() + 1, date.getDate());
    return jdToHijri(jd);
}
function gregorianToJD(year, month, day) {
    if (month <= 2) {
        year -= 1;
        month += 12;
    }
    const A = Math.floor(year / 100);
    const B = 2 - A + Math.floor(A / 4);
    return Math.floor(365.25 * (year + 4716)) + Math.floor(30.6001 * (month + 1)) + day + B - 1524.5;
}
function jdToHijri(jd) {
    const jd1 = Math.floor(jd) + 0.5;
    const year = Math.floor((30 * (jd1 - 1948439.5) + 10646) / 10631);
    const month = Math.min(12, Math.ceil((jd1 - (29 + hijriToJD(year, 1, 1))) / 29.5) + 1);
    const day = Math.floor(jd1 - hijriToJD(year, month, 1)) + 1;
    return {
        year,
        month,
        day: Math.max(1, day),
        monthName: HIJRI_MONTHS_EN[month - 1] ?? '',
        monthNameAr: HIJRI_MONTHS_AR[month - 1] ?? '',
    };
}
function hijriToJD(year, month, day) {
    return Math.floor((11 * year + 3) / 30)
        + 354 * year
        + 30 * month
        - Math.floor((month - 1) / 2)
        + day
        + 1948440 - 385;
}
// ─── Ramadan Check ──────────────────────────────────────────────────
export function isRamadan(date = new Date()) {
    const hijri = toHijri(date);
    return hijri.month === 9; // Ramadan = month 9
}
// ─── Format Hijri Date ──────────────────────────────────────────────
export function formatHijri(date = new Date(), locale = 'ar') {
    const h = toHijri(date);
    if (locale === 'ar') {
        return `${h.day} ${h.monthNameAr} ${h.year} هـ`;
    }
    return `${h.day} ${h.monthName} ${h.year} AH`;
}
// ─── Prayer Times (Aladhan API) ─────────────────────────────────────
const SAUDI_CITIES = {
    'jeddah': { lat: 21.5433, lng: 39.1728 },
    'جدة': { lat: 21.5433, lng: 39.1728 },
    'riyadh': { lat: 24.7136, lng: 46.6753 },
    'الرياض': { lat: 24.7136, lng: 46.6753 },
    'mecca': { lat: 21.4225, lng: 39.8262 },
    'مكة': { lat: 21.4225, lng: 39.8262 },
    'medina': { lat: 24.4672, lng: 39.6024 },
    'المدينة': { lat: 24.4672, lng: 39.6024 },
    'dammam': { lat: 26.4207, lng: 50.0888 },
    'الدمام': { lat: 26.4207, lng: 50.0888 },
    'khobar': { lat: 26.2172, lng: 50.1971 },
    'الخبر': { lat: 26.2172, lng: 50.1971 },
    'abha': { lat: 18.2164, lng: 42.5053 },
    'أبها': { lat: 18.2164, lng: 42.5053 },
    'tabuk': { lat: 28.3835, lng: 36.5662 },
    'تبوك': { lat: 28.3835, lng: 36.5662 },
    'taif': { lat: 21.2703, lng: 40.4158 },
    'الطائف': { lat: 21.2703, lng: 40.4158 },
};
const prayerTimesResponseSchema = z.object({
    data: z.object({
        timings: z.object({
            Fajr: z.string(),
            Sunrise: z.string(),
            Dhuhr: z.string(),
            Asr: z.string(),
            Maghrib: z.string(),
            Isha: z.string(),
        }),
        date: z.object({
            readable: z.string(),
        }),
    }),
});
export async function getPrayerTimes(city) {
    const cityLower = city.toLowerCase().trim();
    const cityKey = Object.keys(SAUDI_CITIES).find(k => cityLower.includes(k));
    // Use city name for API
    const apiCity = cityKey?.replace(/[\u0600-\u06FF]+/, '') || city;
    const displayCity = city;
    const url = new URL('http://api.aladhan.com/v1/timingsByCity');
    url.searchParams.set('city', cityKey && SAUDI_CITIES[cityKey] ? apiCity || city : city);
    url.searchParams.set('country', 'Saudi Arabia');
    url.searchParams.set('method', '4'); // Umm al-Qura University, Makkah
    try {
        const response = await fetch(url.toString(), {
            signal: AbortSignal.timeout(10_000),
        });
        if (!response.ok) {
            throw new Error(`Aladhan API returned ${response.status}`);
        }
        const json = await response.json();
        const parsed = prayerTimesResponseSchema.parse(json);
        return {
            Fajr: parsed.data.timings.Fajr,
            Sunrise: parsed.data.timings.Sunrise,
            Dhuhr: parsed.data.timings.Dhuhr,
            Asr: parsed.data.timings.Asr,
            Maghrib: parsed.data.timings.Maghrib,
            Isha: parsed.data.timings.Isha,
            date: parsed.data.date.readable,
            city: displayCity,
        };
    }
    catch (err) {
        log.error({ city, err }, 'Failed to fetch prayer times');
        throw new Error(`فشل في جلب مواقيت الصلاة لـ ${city}`);
    }
}
// ─── Saudi Working Day ──────────────────────────────────────────────
/**
 * Saudi working week: Sunday (0) through Thursday (4)
 * Weekend: Friday (5) and Saturday (6)
 */
export function isWorkingDay(date = new Date()) {
    const day = date.getDay();
    return day >= 0 && day <= 4; // Sun=0, Mon=1, Tue=2, Wed=3, Thu=4
}
export function getNextWorkingDay(date = new Date()) {
    const next = new Date(date);
    do {
        next.setDate(next.getDate() + 1);
    } while (!isWorkingDay(next));
    return next;
}
// ─── Saudi Phone Formatting (legacy, see phone.ts for full) ─────────
export function formatSaudiPhone(phone) {
    const digits = phone.replace(/\D/g, '');
    if (digits.startsWith('966') && digits.length === 12) {
        return `+${digits}`;
    }
    if (digits.startsWith('05') && digits.length === 10) {
        return `+966${digits.slice(1)}`;
    }
    if (digits.startsWith('5') && digits.length === 9) {
        return `+966${digits}`;
    }
    if (digits.startsWith('00966') && digits.length === 14) {
        return `+${digits.slice(2)}`;
    }
    log.warn({ phone }, 'Could not normalize Saudi phone number');
    return phone;
}
//# sourceMappingURL=hijri.js.map