#!/usr/bin/env python3
"""
Advanced script to extract calendar data from Word document and create Excel file
"""

import pandas as pd
from datetime import datetime
import re
import os
import sys

def create_comprehensive_calendar():
    """
    Create a comprehensive 2026 calendar Excel file
    """
    
    # Create calendar data structure
    calendar_data = []
    
    # Define months and their days
    months = {
        'January': 31,
        'February': 29,  # 2026 is a leap year
        'March': 31,
        'April': 30,
        'May': 31,
        'June': 30,
        'July': 31,
        'August': 31,
        'September': 30,
        'October': 31,
        'November': 30,
        'December': 31
    }
    
    # Create entries for each day of 2026
    for month_name, days_in_month in months.items():
        month_num = list(months.keys()).index(month_name) + 1
        for day in range(1, days_in_month + 1):
            try:
                date_str = f"2026-{month_num:02d}-{day:02d}"
                # Get day of week
                date_obj = datetime.strptime(date_str, '%Y-%m-%d')
                day_of_week = date_obj.strftime('%A')
            except ValueError:
                # Skip invalid dates (like Feb 30)
                continue
            
            calendar_data.append({
                'Date': date_str,
                'Month': month_name,
                'Day': day,
                'Day of Week': day_of_week,
                'Event Name': '',
                'Event Type': '',
                'Notes': ''
            })
    
    # Create DataFrame
    df = pd.DataFrame(calendar_data)
    
    # Save to Excel with multiple sheets
    output_file = '/var/www/html/wordpress6/wordpress/EP/2026_complete_calendar.xlsx'
    
    with pd.ExcelWriter(output_file, engine='openpyxl') as writer:
        # Main calendar sheet
        df.to_excel(writer, sheet_name='Full Calendar', index=False)
        
        # Create individual month sheets
        for month_name in months.keys():
            month_data = df[df['Month'] == month_name].copy()
            month_data.to_excel(writer, sheet_name=month_name, index=False)
        
        # Create summary sheet
        summary_data = []
        for month_name in months.keys():
            month_events = df[df['Month'] == month_name]
            events_count = len(month_events[month_events['Event Name'] != ''])
            summary_data.append({
                'Month': month_name,
                'Total Days': len(month_events),
                'Events Scheduled': events_count,
                'Days Available': len(month_events) - events_count
            })
        
        summary_df = pd.DataFrame(summary_data)
        summary_df.to_excel(writer, sheet_name='Summary', index=False)
    
    print(f"Complete calendar created: {output_file}")
    print(f"Total entries: {len(calendar_data)}")
    print("Sheets created:")
    print("- Full Calendar (all days)")
    print("- Individual month sheets")
    print("- Summary sheet")
    
    return output_file

def create_january_with_events():
    """
    Create January 2026 with the known events
    """
    january_events = [
        ('2026-01-01', 'NEW YEARS DAY SCRAMBLE', 'Tournament'),
        ('2026-01-02', 'EPIC LADIES - Q MEN', 'Regular Event'),
        ('2026-01-03', 'MENS 60 TEES LADIES 52\'S', 'Regular Event'),
        ('2026-01-04', 'SCRAMBLE', 'Regular Event'),
        ('2026-01-05', 'EPIC LADIES (a.m), 321 (Draw), MEN- Q (p.m)', 'Regular Event'),
        ('2026-01-07', 'MATCHPLAY PRESIDENT VS CAPTAINS', 'Match Play'),
        ('2026-01-09', 'EPIC LADIES - Q MEN', 'Regular Event'),
        ('2026-01-10', 'MENS 60 TEES LADIES 52\'S', 'Regular Event'),
        ('2026-01-11', 'SCRAMBLE', 'Regular Event'),
        ('2026-01-12', 'COURSE CLOSED', 'Course Maintenance'),
        ('2026-01-13', 'COURSE CLOSED', 'Course Maintenance'),
        ('2026-01-14', 'COURSE CLOSED', 'Course Maintenance'),
        ('2026-01-16', 'EPIC LADIES MEN', 'Regular Event'),
        ('2026-01-17', 'MENS 60 TEES LADIES 52\'S', 'Regular Event'),
        ('2026-01-18', 'SCRAMBLE', 'Regular Event'),
        ('2026-01-19', 'EPIC LADIES (p.m), Yellow ball MEN (a.m)', 'Regular Event'),
        ('2026-01-21', 'MEDAL STABLEFORD 9-HOLE QUALIFIERS', 'Qualifier'),
        ('2026-01-23', 'EPIC LADIES MEN', 'Regular Event'),
        ('2026-01-24', 'MENS 60 TEES LADIES 52\'S', 'Regular Event'),
        ('2026-01-25', 'SCRAMBLE', 'Regular Event'),
        ('2026-01-26', 'EPIC - Q LADIES (a.m)- Q MEN (p.m)', 'Regular Event'),
        ('2026-01-28', 'TEAM AM/AM (DRAW)', 'Team Event'),
        ('2026-01-30', 'EPIC LADIES MEN', 'Regular Event'),
        ('2026-01-31', 'MENS 60 TEES LADIES 52\'S', 'Regular Event')
    ]
    
    # Create DataFrame
    df = pd.DataFrame(january_events, columns=['Date', 'Event Name', 'Event Type'])
    df['Month'] = 'January'
    df['Day'] = df['Date'].str.extract(r'-(\d{2})$').astype(int)
    df['Day of Week'] = pd.to_datetime(df['Date']).dt.day_name()
    
    # Add empty notes column
    df['Notes'] = ''
    
    # Reorder columns
    df = df[['Date', 'Month', 'Day', 'Day of Week', 'Event Name', 'Event Type', 'Notes']]
    
    # Save to Excel
    output_file = '/var/www/html/wordpress6/wordpress/EP/january_2026_with_events.xlsx'
    df.to_excel(output_file, index=False, sheet_name='January 2026')
    
    print(f"January with events created: {output_file}")
    return output_file

def create_instructions():
    """
    Create instructions for populating the calendar
    """
    instructions = """
# Instructions for Populating the 2026 Calendar Excel File

## Files Created:
1. 2026_complete_calendar.xlsx - Full year template with all days
2. january_2026_with_events.xlsx - January with sample events

## How to populate the full calendar:

### Method 1: Manual Entry
1. Open the Word document (2026-calendar.V6.docx)
2. Open the Excel file (2026_complete_calendar.xlsx)
3. For each month:
   - Go to the corresponding month sheet
   - Copy event names from the Word document
   - Paste them into the 'Event Name' column for the correct dates
   - Add event types in the 'Event Type' column
   - Add any notes in the 'Notes' column

### Method 2: Copy from Word to Excel
1. Open the Word document
2. Select and copy the calendar text
3. Paste into a text editor first to clean up formatting
4. Copy the cleaned text into Excel

### Event Types to Use:
- Tournament
- Regular Event
- Match Play
- Course Maintenance
- Qualifier
- Team Event
- Special Event

### Tips:
- Use the 'Full Calendar' sheet to see all days at once
- Use individual month sheets for detailed editing
- The 'Summary' sheet will show statistics once populated
- Save frequently while working

## Next Steps:
1. Open the Excel file
2. Start with January (already populated as example)
3. Work through each month systematically
4. Save the completed file
"""
    
    with open('/var/www/html/wordpress6/wordpress/EP/calendar_instructions.txt', 'w') as f:
        f.write(instructions)
    
    print("Instructions created: calendar_instructions.txt")

if __name__ == "__main__":
    try:
        print("Creating comprehensive 2026 calendar...")
        
        # Create the complete calendar template
        full_calendar = create_comprehensive_calendar()
        
        # Create January with events as example
        january_example = create_january_with_events()
        
        # Create instructions
        create_instructions()
        
        print("\n=== FILES CREATED ===")
        print(f"1. Complete calendar template: {full_calendar}")
        print(f"2. January example: {january_example}")
        print("3. Instructions: calendar_instructions.txt")
        
        print("\n=== NEXT STEPS ===")
        print("1. Open the Word document (2026-calendar.V6.docx)")
        print("2. Open the Excel file (2026_complete_calendar.xlsx)")
        print("3. Copy event data from Word to Excel")
        print("4. Save the completed Excel file")
        
    except Exception as e:
        print(f"Error: {e}")
        print("Make sure pandas and openpyxl are installed:")
        print("pip install pandas openpyxl")
