#!/usr/bin/env python3
"""
Timezone-aware daily briefing system for Keith (Mountain Standard Time)
"""

import os
import subprocess
from datetime import datetime, timedelta

# Set Keith's timezone using TZ environment variable
os.environ['TZ'] = 'America/Denver'

def get_keith_time():
    """Get current time in Keith's timezone"""
    return datetime.now()

def get_business_dates(start_date, num_days=5):
    """Get next N business days starting from start_date"""
    business_days = []
    current = start_date
    
    while len(business_days) < num_days:
        if current.weekday() < 5:  # Monday=0, Friday=4
            business_days.append(current)
        current += timedelta(days=1)
    
    return business_days

def run_gog_interactive(cmd_parts):
    """Run gog command interactively (for cron jobs)"""
    try:
        # In isolated sessions, we can use interactive mode
        result = subprocess.run(
            cmd_parts,
            capture_output=True,
            text=True,
            input="\n",  # Empty keyring password
            timeout=30
        )
        return result.stdout if result.returncode == 0 else None
    except Exception as e:
        print(f"Error running gog: {e}")
        return None

def create_daily_brief_with_real_data():
    """Create daily briefs with real calendar data"""
    
    print(f"Running timezone-aware briefing system...")
    keith_now = get_keith_time()
    print(f"Keith's current time: {keith_now.strftime('%A %B %d, %Y at %I:%M %p MST')}")
    
    # Get next 5 business days
    today = keith_now.date()
    business_dates = get_business_dates(today, 5)
    
    print(f"Creating briefs for:")
    for date in business_dates:
        print(f"  - {date.strftime('%A %B %d, %Y')}")
    
    # Get calendar data
    calendar_output = run_gog_interactive([
        'gog', 'calendar', 'list', '-n', '20', '-a', 'keith@atomicelevator.com'
    ])
    
    if calendar_output:
        print("✓ Calendar data retrieved successfully")
    else:
        print("⚠ Using placeholder data (calendar access failed)")
        
    return business_dates

if __name__ == "__main__":
    dates = create_daily_brief_with_real_data()