#!/home/user/adhan/venv/bin/python3
"""
Fetch daily prayer times from Aladhan API and schedule at jobs.
Run this once per day via cron at midnight.
"""
import os
import sys
import subprocess
import requests
from datetime import datetime

CONFIG_FILE = "/home/user/adhan/config.env"
config = {}
with open(CONFIG_FILE) as f:
    for line in f:
        line = line.strip()
        if line and not line.startswith("#") and "=" in line:
            key, val = line.split("=", 1)
            config[key.strip()] = val.strip()

CITY = config["CITY"]
COUNTRY = config["COUNTRY"]
METHOD = config["METHOD"]
CAST_SCRIPT = "/home/user/adhan/cast_adhan.py"
VENV_PYTHON = config.get("VENV_PYTHON", "/home/user/adhan/venv/bin/python")

PRAYERS = ["Fajr", "Dhuhr", "Asr", "Maghrib", "Isha"]
ALADHAN_URL = "http://api.aladhan.com/v1/timingsByCity"


def fetch_prayer_times():
    params = {"city": CITY, "country": COUNTRY, "method": METHOD}
    try:
        resp = requests.get(ALADHAN_URL, params=params, timeout=15)
        resp.raise_for_status()
        data = resp.json()
        timings = data["data"]["timings"]
        return {p: timings[p] for p in PRAYERS}
    except Exception as e:
        print(f"[ERROR] Failed to fetch prayer times: {e}", file=sys.stderr)
        sys.exit(1)


def clear_old_jobs():
    result = subprocess.run(["atq"], capture_output=True, text=True)
    for line in result.stdout.strip().split("\n"):
        if line.strip():
            job_id = line.strip().split()[0]
            subprocess.run(["atrm", job_id], capture_output=True)


def schedule_job(prayer_name, time_str):
    cmd = "{} {} \"{}\"".format(VENV_PYTHON, CAST_SCRIPT, prayer_name)
    try:
        result = subprocess.run(
            ["at", time_str],
            input=cmd + "\n",
            capture_output=True,
            text=True,
        )
        if result.returncode == 0:
            print("  [OK] {} scheduled for {}".format(prayer_name, time_str))
        else:
            print("  [FAIL] {} at {}: {}".format(prayer_name, time_str, result.stderr.strip()))
    except Exception as e:
        print("  [ERROR] {}: {}".format(prayer_name, e))


def main():
    now_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    print("[{}] Fetching prayer times for {}, {} (method {})...".format(
        now_str, CITY, COUNTRY, METHOD))
    prayer_times = fetch_prayer_times()
    print("Clearing old jobs...")
    clear_old_jobs()
    print("Scheduling prayers:")
    for prayer in PRAYERS:
        time_str = prayer_times.get(prayer)
        if time_str:
            schedule_job(prayer, time_str)
        else:
            print("  [WARN] {} time not found".format(prayer))
    print("Done. Use atq to view scheduled jobs.")


if __name__ == "__main__":
    main()
