#!/usr/bin/env python3
"""
Fetch verse of the day from OurManna API.
Falls back to curated ESV Reformed verses if API unavailable.
"""

import json
import sys
import urllib.request
import urllib.error
from datetime import datetime

OURMANNA_URL = "https://beta.ourmanna.com/api/v1/get?format=json&order=daily"

FALLBACK_VERSES = [
    {"text": "For I am sure that neither death nor life, nor angels nor rulers, nor things present nor things to come, nor powers, nor height nor depth, nor anything else in all creation, will be able to separate us from the love of God in Christ Jesus our Lord.", "reference": "Romans 8:38-39", "version": "ESV"},
    {"text": "I have been crucified with Christ. It is no longer I who live, but Christ who lives in me. And the life I now live in the flesh I live by faith in the Son of God, who loved me and gave himself for me.", "reference": "Galatians 2:20", "version": "ESV"},
    {"text": "The LORD is my shepherd; I shall not want.", "reference": "Psalm 23:1", "version": "ESV"},
    {"text": "For by grace you have been saved through faith. And this is not your own doing; it is the gift of God, not a result of works, so that no one may boast.", "reference": "Ephesians 2:8-9", "version": "ESV"},
    {"text": "Come to me, all who labor and are heavy laden, and I will give you rest.", "reference": "Matthew 11:28", "version": "ESV"},
    {"text": "Trust in the LORD with all your heart, and do not lean on your own understanding. In all your ways acknowledge him, and he will make straight your paths.", "reference": "Proverbs 3:5-6", "version": "ESV"},
    {"text": "And we know that for those who love God all things work together for good, for those who are called according to his purpose.", "reference": "Romans 8:28", "version": "ESV"},
    {"text": "I can do all things through him who strengthens me.", "reference": "Philippians 4:13", "version": "ESV"},
    {"text": "But he said to me, 'My grace is sufficient for you, for my power is made perfect in weakness.'", "reference": "2 Corinthians 12:9", "version": "ESV"},
    {"text": "The heart of man plans his way, but the LORD establishes his steps.", "reference": "Proverbs 16:9", "version": "ESV"},
    {"text": "Do not be anxious about anything, but in everything by prayer and supplication with thanksgiving let your requests be made known to God.", "reference": "Philippians 4:6", "version": "ESV"},
    {"text": "For God so loved the world, that he gave his only Son, that whoever believes in him should not perish but have eternal life.", "reference": "John 3:16", "version": "ESV"},
    {"text": "God is our refuge and strength, a very present help in trouble.", "reference": "Psalm 46:1", "version": "ESV"},
    {"text": "The LORD bless you and keep you; the LORD make his face shine on you and be gracious to you.", "reference": "Numbers 6:24-25", "version": "ESV"},
]


def fetch_api_verse():
    """Fetch from OurManna API. Returns dict or None on failure."""
    try:
        req = urllib.request.Request(
            OURMANNA_URL,
            headers={"User-Agent": "OpenClaw-DailyDevotion/1.0"}
        )
        with urllib.request.urlopen(req, timeout=8) as resp:
            data = json.loads(resp.read().decode())
            details = data["verse"]["details"]
            return {
                "text": details["text"].strip(),
                "reference": details["reference"],
                "version": details.get("version", "NIV"),
                "source": "ourmanna"
            }
    except Exception as e:
        print(f"[API unavailable: {e}] Using fallback verse.", file=sys.stderr)
        return None


def get_fallback_verse():
    """Return a curated verse based on day of year."""
    day_of_year = datetime.now().timetuple().tm_yday
    verse = FALLBACK_VERSES[day_of_year % len(FALLBACK_VERSES)]
    return {**verse, "source": "fallback"}


def main():
    verse = fetch_api_verse() or get_fallback_verse()
    print(json.dumps(verse, indent=2))


if __name__ == "__main__":
    main()
