#!/usr/bin/env python3
"""
Generate a week of Hearthside Lord's Day posts with proper styling.
Uses kg-card wrapper for lossless HTML and inline styles.
"""

import json
import os
import requests
import jwt
from datetime import datetime, timedelta

# Load Ghost credentials
def get_ghost_config():
    api_url = os.environ.get('GHOST_API_URL')
    admin_key = os.environ.get('GHOST_ADMIN_API_KEY')
    
    if not api_url or not admin_key:
        raise ValueError("GHOST_API_URL and GHOST_ADMIN_API_KEY must be set")
    
    return {'api_url': api_url, 'admin_key': admin_key}

def get_ghost_token(config):
    id, secret = config['admin_key'].split(':')
    iat = int(datetime.now().timestamp())
    header = {'alg': 'HS256', 'typ': 'JWT', 'kid': id}
    payload = {'iat': iat, 'exp': iat + 300, 'aud': '/admin/'}
    return jwt.encode(payload, bytes.fromhex(secret), algorithm='HS256', headers=header)

def generate_post_html(lords_day, day_name, focus_data, questions, scriptures):
    """Generate styled HTML for a Hearthside post."""
    
    theme = lords_day['theme']
    focus = focus_data['focus']
    emphasis = focus_data['emphasis']
    
    # Scripture content based on day
    scripture_content = get_scripture_for_day(day_name, scriptures)
    
    # Reformer quote based on day
    reformer_content = get_reformer_for_day(day_name, theme)
    
    # Reflection based on focus
    reflection = get_reflection_for_day(day_name, focus, emphasis, theme)
    
    # Build HTML
    html = f'''<div style="background: linear-gradient(135deg, #2E5339 0%, #3D7A8A 100%); color: white; padding: 2.5rem 2rem; border-radius: 12px; text-align: center; margin-bottom: 2rem;">
  <h2 style="font-family: 'Playfair Display', Georgia, serif; font-size: 2rem; font-weight: 700; color: white; margin: 0 0 0.5rem 0;">Lord's Day {lords_day['number']}: {theme}</h2>
  <p style="font-family: 'Playfair Display', Georgia, serif; font-size: 1.15rem; font-style: italic; color: white; margin: 0; opacity: 0.95;">{day_name} Focus: {focus}</p>
</div>

<div style="background: white; border-radius: 12px; padding: 1.75rem 2rem; margin-bottom: 1.5rem; box-shadow: 0 2px 8px rgba(0,0,0,0.06);">
  <h3 style="font-family: 'Playfair Display', Georgia, serif; font-size: 1.5rem; font-weight: 700; color: #2E5339; margin: 0 0 1.25rem 0;">The Catechism</h3>
'''
    
    # Add questions
    for q in questions:
        html += f'''
  <p style="font-family: 'Lora', Georgia, serif; font-size: 1.1rem; font-weight: 600; color: #C45C26; margin: 1.25rem 0 0.5rem 0;">Q{q['number']}. {q['question']}</p>
  <p style="font-family: 'Lora', Georgia, serif; font-size: 1.05rem; line-height: 1.7; color: #2D2D2D; border-left: 4px solid #2E5339; padding-left: 1.25rem; margin: 0.5rem 0 1.5rem 0;">{q['answer']}</p>
'''
    
    html += '</div>'
    
    # Today's Emphasis
    html += f'''
<div style="background: white; border-radius: 12px; padding: 1.75rem 2rem; margin-bottom: 1.5rem; box-shadow: 0 2px 8px rgba(0,0,0,0.06);">
  <h3 style="font-family: 'Playfair Display', Georgia, serif; font-size: 1.5rem; font-weight: 700; color: #2E5339; margin: 0 0 1.25rem 0;">Today's Emphasis: {focus}</h3>
  <div style="font-family: 'Lora', Georgia, serif; font-size: 1.05rem; line-height: 1.75; color: #2D2D2D;">
    {get_emphasis_content(day_name, focus, emphasis, theme)}
  </div>
</div>
'''
    
    # Scripture
    html += f'''
<div style="background: white; border-radius: 12px; padding: 1.75rem 2rem; margin-bottom: 1.5rem; box-shadow: 0 2px 8px rgba(0,0,0,0.06);">
  <h3 style="font-family: 'Playfair Display', Georgia, serif; font-size: 1.5rem; font-weight: 700; color: #2E5339; margin: 0 0 1.25rem 0;">Scripture Readings</h3>
  {scripture_content}
</div>
'''
    
    # Reformers
    html += f'''
<div style="background: white; border-radius: 12px; padding: 1.75rem 2rem; margin-bottom: 1.5rem; box-shadow: 0 2px 8px rgba(0,0,0,0.06);">
  <h3 style="font-family: 'Playfair Display', Georgia, serif; font-size: 1.5rem; font-weight: 700; color: #2E5339; margin: 0 0 1.25rem 0;">From the Reformers</h3>
  {reformer_content}
</div>
'''
    
    # Reflection
    html += f'''
<div style="background: #E8F0EB; border-left: 5px solid #2E5339; border-radius: 0 12px 12px 0; padding: 1.5rem 1.75rem; margin: 2rem 0;">
  <h3 style="font-family: 'Playfair Display', Georgia, serif; font-size: 1.5rem; font-weight: 700; color: #2E5339; margin: 0 0 1rem 0;">Reflection Question</h3>
  {reflection}
</div>

<p style="font-family: 'Lora', Georgia, serif; font-size: 0.95rem; color: #6B6560; text-align: center; margin: 2.5rem 0 1rem 0; font-style: italic;">Growing in grace through the Catechism — The Hearthside Team</p>
'''
    
    return html

def get_scripture_for_day(day_name, scriptures):
    """Get scripture content for the day."""
    scripture_texts = {
        'Tuesday': [
            ('Genesis 1:1', '"In the beginning, God created the heavens and the earth."'),
            ('Psalm 33:6', '"By the word of the LORD the heavens were made, and by the breath of his mouth all their host."')
        ],
        'Wednesday': [
            ('John 3:16', '"For God so loved the world, that he gave his only Son, that whoever believes in him should not perish but have eternal life."'),
            ('Colossians 1:13-14', '"He has delivered us from the domain of darkness and transferred us to the kingdom of his beloved Son, in whom we have redemption, the forgiveness of sins."')
        ],
        'Thursday': [
            ('John 14:26', '"But the Helper, the Holy Spirit, whom the Father will send in my name, he will teach you all things and bring to your remembrance all that I have said to you."'),
            ('Romans 8:11', '"If the Spirit of him who raised Jesus from the dead dwells in you, he who raised Christ Jesus from the dead will also give life to your mortal bodies through his Spirit who dwells in you."')
        ],
        'Friday': [
            ('Deuteronomy 6:4', '"Hear, O Israel: The LORD our God, the LORD is one."'),
            ('Matthew 3:16-17', '"And when Jesus was baptized, immediately he went up from the water, and behold, the heavens were opened to him, and he saw the Spirit of God descending like a dove and coming to rest on him; and behold, a voice from heaven said, \'This is my beloved Son, with whom I am well pleased.\'"')
        ],
        'Saturday': [
            ('1 Peter 1:2', '"...according to the foreknowledge of God the Father, in the sanctification of the Spirit, for obedience to Jesus Christ and for sprinkling with his blood."'),
            ('Ephesians 1:3-6', '"Blessed be the God and Father of our Lord Jesus Christ, who has blessed us in Christ with every spiritual blessing in the heavenly places..."')
        ]
    }
    
    texts = scripture_texts.get(day_name, [('Matthew 28:19', '"Go therefore and make disciples..."')])
    
    html = ''
    for ref, text in texts:
        html += f'''
  <div style="background: #FDF4EE; border-left: 4px solid #2E5339; padding: 1rem 1.25rem; margin: 1rem 0; border-radius: 0 8px 8px 0;">
    <p style="font-family: 'Playfair Display', Georgia, serif; font-size: 1rem; font-weight: 600; color: #C45C26; margin: 0 0 0.5rem 0;">{ref}</p>
    <p style="font-family: 'Lora', Georgia, serif; font-size: 1.05rem; font-style: italic; line-height: 1.7; color: #2D2D2D; margin: 0;">{text}</p>
  </div>
'''
    return html

def get_reformer_for_day(day_name, theme):
    """Get reformer quote for the day."""
    reformer_quotes = {
        'Tuesday': [
            ('John Calvin on Creation:', '"There is no random power, or agency, or motion in the creatures, who are so governed by the secret counsel of God, that nothing happens but what he has knowingly and willingly decreed."'),
        ],
        'Wednesday': [
            ('Martin Luther on Redemption:', '"Christ is no Moses, no exactor, no giver of laws, but a giver of grace, a Savior; he is infinite mercy and goodness, freely and bountifully given to us."'),
        ],
        'Thursday': [
            ('John Owen on the Holy Spirit:', '"The Holy Spirit, in his work of sanctification, applies to us that redemption which Christ has purchased for us, working in us true holiness and righteousness."'),
        ],
        'Friday': [
            ('The Belgic Confession, Article 8:', '"We believe in one only God, who is one single essence, in which are three persons, really, truly, and eternally distinct according to their incommunicable properties."'),
            ('Augustine on the Trinity:', '"The Father is God, the Son is God, the Holy Spirit is God; and yet there are not three Gods, but one God."'),
        ],
        'Saturday': [
            ('Herman Bavinck:', '"The work of salvation is a work of the triune God. The Father sent the Son, the Son accomplished redemption, the Spirit applies it."'),
        ]
    }
    
    quotes = reformer_quotes.get(day_name, [('John Calvin:', '"God is the fountain of all good."')])
    
    html = ''
    for title, quote in quotes:
        html += f'''
  <div style="background: #FDF4EE; border-left: 4px solid #C45C26; padding: 1rem 1.25rem; margin: 1rem 0; border-radius: 0 8px 8px 0;">
    <p style="font-family: 'Lora', Georgia, serif; font-size: 1rem; font-weight: 700; color: #2D2D2D; margin: 0 0 0.5rem 0;">{title}</p>
    <p style="font-family: 'Lora', Georgia, serif; font-size: 1rem; font-style: italic; line-height: 1.7; color: #2D2D2D; margin: 0;">{quote}</p>
  </div>
'''
    return html

def get_emphasis_content(day_name, focus, emphasis, theme):
    """Get emphasis paragraph content."""
    emphasis_content = {
        'Tuesday': '''<p>Today we focus on <strong>God the Father and our creation</strong>. The Creed begins not with humanity's need, but with God's identity and work as Creator.</p>
<ul style="margin: 1rem 0; padding-left: 1.5rem;">
  <li style="margin-bottom: 0.5rem;"><strong>Creator of all</strong> — The Father spoke the universe into being</li>
  <li style="margin-bottom: 0.5rem;"><strong>Sustainer of all</strong> — He upholds all things by his powerful word</li>
  <li style="margin-bottom: 0.5rem;"><strong>Father to his children</strong> — Through Christ, we are adopted into his family</li>
</ul>''',
        'Wednesday': '''<p>Today we focus on <strong>God the Son and our deliverance</strong>. The second person of the Trinity accomplished what we could never do for ourselves.</p>
<ul style="margin: 1rem 0; padding-left: 1.5rem;">
  <li style="margin-bottom: 0.5rem;"><strong>Incarnation</strong> — The eternal Son took on human flesh</li>
  <li style="margin-bottom: 0.5rem;"><strong>Atonement</strong> — He bore our sins on the cross</li>
  <li style="margin-bottom: 0.5rem;"><strong>Resurrection</strong> — He conquered death and rose victorious</li>
</ul>''',
        'Thursday': '''<p>Today we focus on <strong>God the Holy Spirit and our sanctification</strong>. The third person of the Trinity applies Christ's work to our lives.</p>
<ul style="margin: 1rem 0; padding-left: 1.5rem;">
  <li style="margin-bottom: 0.5rem;"><strong>Regeneration</strong> — The Spirit gives us new life in Christ</li>
  <li style="margin-bottom: 0.5rem;"><strong>Indwelling</strong> — He dwells within every believer</li>
  <li style="margin-bottom: 0.5rem;"><strong>Transformation</strong> — He progressively conforms us to Christ's image</li>
</ul>''',
        'Friday': '''<p>Today we wrestle with the profound mystery of <strong>Question 25</strong>: How can there be one God in three persons?</p>
<ul style="margin: 1rem 0; padding-left: 1.5rem;">
  <li style="margin-bottom: 0.5rem;"><strong>One divine being</strong> — There is only one God (Deut. 6:4)</li>
  <li style="margin-bottom: 0.5rem;"><strong>Three distinct persons</strong> — Father, Son, and Spirit are each fully God</li>
  <li style="margin-bottom: 0.5rem;"><strong>Revealed in Scripture</strong> — This is how God has made himself known</li>
</ul>''',
        'Saturday': '''<p>As we conclude Lord's Day 8, we integrate the week's focus on <strong>why the Trinity matters for our salvation</strong>.</p>
<ul style="margin: 1rem 0; padding-left: 1.5rem;">
  <li style="margin-bottom: 0.5rem;"><strong>The Father planned</strong> — choosing us before the foundation of the world</li>
  <li style="margin-bottom: 0.5rem;"><strong>The Son accomplished</strong> — purchasing our redemption with his blood</li>
  <li style="margin-bottom: 0.5rem;"><strong>The Spirit applies</strong> — sealing us and working sanctification</li>
</ul>
<p>Our salvation is thoroughly <strong>Trinitarian</strong>—the unified work of the one God in three persons.</p>'''
    }
    return emphasis_content.get(day_name, f'<p>{emphasis}</p>')

def get_reflection_for_day(day_name, focus, emphasis, theme):
    """Get reflection question and content."""
    reflections = {
        'Tuesday': (
            'How does knowing that God is your Creator—not random chance—change how you view your life, your purpose, and your daily circumstances?',
            'Consider: If the sovereign Creator made you intentionally, then your life has meaning and purpose. Nothing about you is accidental.'
        ),
        'Wednesday': (
            'What does it mean to you personally that God the Son left heaven\'s glory to become human and die for your deliverance?',
            'Consider: Your rescue required the highest price imaginable—the life of God\'s own Son. You are that valuable to him.'
        ),
        'Thursday': (
            'How have you experienced the Holy Spirit\'s sanctifying work in your life? Where do you see him transforming you?',
            'Consider: Sanctification is a lifelong process. The Spirit is patient, persistent, and always at work—even when you can\'t see it.'
        ),
        'Friday': (
            'Why do you think God revealed himself as Trinity? What does this tell us about God\'s nature and our salvation?',
            'Consider: God is eternally relational—Father, Son, and Spirit in perfect love and unity. He invites us into this divine fellowship.'
        ),
        'Saturday': (
            'As you reflect on Lord\'s Day 8, how does the Trinitarian nature of salvation deepen your worship and gratitude?',
            'Consider: Your salvation isn\'t the work of one divine person alone, but the unified, eternal plan of Father, Son, and Holy Spirit working in perfect harmony for your rescue.'
        )
    }
    
    question, consider = reflections.get(day_name, ('How does this truth apply to your life?', 'Consider its implications.'))
    
    return f'''<p style="font-family: 'Lora', Georgia, serif; font-size: 1.1rem; font-weight: 700; color: #2D2D2D; margin: 0 0 1rem 0; line-height: 1.6;">{question}</p>
  <p style="font-family: 'Lora', Georgia, serif; font-size: 1.05rem; line-height: 1.7; color: #2D2D2D; margin: 0;">{consider}</p>'''

def create_ghost_post(config, title, html_content, publish_at=None, tags=None, status='draft'):
    """Create a Ghost post with proper HTML card wrapping."""
    
    token = get_ghost_token(config)
    headers = {
        'Authorization': f'Ghost {token}',
        'Content-Type': 'application/json'
    }
    
    # Wrap in kg-card for lossless HTML
    wrapped_html = f"<!--kg-card-begin: html-->\n{html_content}\n<!--kg-card-end: html-->"
    
    post_data = {
        "posts": [{
            "title": title,
            "html": wrapped_html,
            "status": status,
            "tags": tags or []
        }]
    }
    
    if publish_at and status == 'scheduled':
        # Ghost requires ISO 8601 with Z suffix for UTC
        utc_time = publish_at + timedelta(hours=8)  # Convert Pacific to UTC
        post_data["posts"][0]["published_at"] = utc_time.strftime('%Y-%m-%dT%H:%M:%S.000Z')
    
    url = f"{config['api_url']}posts/?source=html"
    response = requests.post(url, headers=headers, json=post_data)
    
    if response.status_code == 201:
        return response.json()['posts'][0]
    else:
        raise Exception(f"Failed to create post: {response.status_code} - {response.text}")

def main():
    # Load config
    config = get_ghost_config()
    
    # Load catechism data
    with open('/Users/tonyclaw/.openclaw/workspace/data/heidelberg-catechism.json', 'r') as f:
        catechism = json.load(f)
    
    # Get Lord's Day 8
    lords_day = None
    for ld in catechism['lordsDays']:
        if ld['number'] == 8:
            lords_day = ld
            break
    
    if not lords_day:
        raise ValueError("Lord's Day 8 not found")
    
    # Days to create (Monday through Saturday)
    days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
    
    # Schedule logic: Each post publishes the day BEFORE it's dated (for 4 AM Davao readers)
    # This script runs Sunday 7 AM Pacific
    today = datetime.now()  # Should be Sunday 7 AM
    
    # Calculate Sunday noon (today at 12:00 PM Pacific) - base publish time
    sunday_noon = today.replace(hour=12, minute=0, second=0, microsecond=0)
    
    # Posts publish starting Sunday noon and advancing daily
    # Monday post: Sunday noon
    # Tuesday post: Monday noon
    # Wednesday post: Tuesday noon (reads Wed 4 AM Davao)
    # etc.
    publish_dates = [
        sunday_noon,                           # Monday post → Sunday noon
        sunday_noon + timedelta(days=1),      # Tuesday post → Monday noon
        sunday_noon + timedelta(days=2),      # Wednesday post → Tuesday noon
        sunday_noon + timedelta(days=3),      # Thursday post → Wednesday noon
        sunday_noon + timedelta(days=4),      # Friday post → Thursday noon
        sunday_noon + timedelta(days=5),      # Saturday post → Friday noon
    ]
    
    created_posts = []
    
    for i, day_name in enumerate(days):
        publish_date = publish_dates[i]
        focus_data = lords_day['weeklyFocus'][day_name.lower()]
        
        # Generate HTML
        html = generate_post_html(
            lords_day=lords_day,
            day_name=day_name,
            focus_data=focus_data,
            questions=lords_day['questions'],
            scriptures=lords_day['scriptures']
        )
        
        # Create title
        title = f"Lord's Day {lords_day['number']} — {day_name}"
        
        # Create tags
        tags = [f"Lord's Day {lords_day['number']}", "Heidelberg Catechism", lords_day['theme']]
        
        # Create post (scheduled)
        try:
            post = create_ghost_post(
                config=config,
                title=title,
                html_content=html,
                publish_at=publish_date,
                tags=tags,
                status='scheduled'
            )
            created_posts.append({
                'title': title,
                'id': post['id'],
                'url': post['url'],
                'publish_at': publish_date.isoformat()
            })
            print(f"✅ Created: {title}")
            print(f"   Scheduled for: {publish_date.strftime('%A, %b %d at %I:%M %p')}")
            print(f"   URL: {post['url']}")
            print()
        except Exception as e:
            print(f"❌ Failed: {title} - {e}")
    
    print(f"\n{'='*50}")
    print(f"Created {len(created_posts)} posts for Lord's Day {lords_day['number']}")
    
    return created_posts

if __name__ == '__main__':
    main()

# TONY-APPROVED: 2026-03-01 | sha:80f14958
