#!/usr/bin/env python3
"""
Strategic Brief System - Integrates priorities, relationships, and intelligence
"""

import json
import subprocess
import os
from datetime import datetime, timedelta

def load_priorities():
    """Load current rocks and sprint goals"""
    try:
        with open('KEITH-PRIORITIES.md', 'r') as f:
            return f.read()
    except:
        return "No priorities file found"

def load_relationships():
    """Load relationship intelligence"""
    try:
        with open('BUSINESS-RELATIONSHIPS.md', 'r') as f:
            return f.read()
    except:
        return "No relationships file found"

def get_calendar_for_date(target_date):
    """Get calendar for specific date via gog CLI"""
    try:
        date_str = target_date.strftime('%Y-%m-%d')
        next_date = (target_date + timedelta(days=1)).strftime('%Y-%m-%d')
        
        result = subprocess.run([
            'bash', '-c', 
            f'source ~/.gog_env && gog calendar events primary --from "{date_str}T00:00:00Z" --to "{next_date}T00:00:00Z" --account keith@atomicelevator.com'
        ], capture_output=True, text=True)
        
        if result.returncode == 0:
            return result.stdout
        else:
            return f"Calendar error: {result.stderr}"
    except:
        return "Calendar unavailable"

def get_calendar_today():
    """Get today's calendar via gog CLI"""
    return get_calendar_for_date(datetime.now())

def get_recent_emails():
    """Get recent emails for intelligence"""
    try:
        result = subprocess.run([
            'bash', '-c', 
            'source ~/.gog_env && gog gmail messages search "newer_than:1d" --max 20 --account keith@atomicelevator.com'
        ], capture_output=True, text=True)
        
        if result.returncode == 0:
            return result.stdout
        else:
            return f"Email error: {result.stderr}"
    except:
        return "Email unavailable"

def analyze_power_hour_opportunity(priorities, calendar, emails, target_date):
    """Recommend ONE high-leverage activity for power hour"""
    
    power_hour_options = [
        {
            "activity": "Real Estate Edition Demo Refinement",
            "rationale": "Perfect demo closes Joe's 70 clients faster + supports $50K MRR rock",
            "leverage": "1 hour investment → 10x demo conversion rate"
        },
        {
            "activity": "KC Tolliver Investment Proposal",
            "rationale": "Clear proposal gets to $250K funding goal faster",
            "leverage": "1 perfect document → $200K funding decision"
        },
        {
            "activity": "Enterprise Onboarding Process",
            "rationale": "Standardized process accelerates all 3 enterprise deals",
            "leverage": "1 system → 3 deals move faster simultaneously"
        },
        {
            "activity": "Floyd's In-Person Meeting Agenda",
            "rationale": "Perfect agenda converts Denver meeting to signed deal",
            "leverage": "1 strategic document → enterprise client conversion"
        },
        {
            "activity": "Multi-Site Pilot Program Design",
            "rationale": "Reusable pilot structure for Young Life, Focus Financial, Floyd's",
            "leverage": "1 framework → 3 prospects use same proven approach"
        },
        {
            "activity": "Colibri Marketing Assets Creation",
            "rationale": "Perfect assets enable Diana's luxury real estate launch in April",
            "leverage": "1 asset suite → entire market vertical opens"
        },
        {
            "activity": "Moroccanoil Enterprise Proposal",
            "rationale": "Beauty industry breakthrough with major brand",
            "leverage": "1 custom proposal → $25K+ MRR enterprise deal"
        }
    ]
    
    # Selection based on target date's day of week
    day_index = target_date.weekday() % len(power_hour_options)
    return power_hour_options[day_index]

def create_daily_strategic_brief(target_date=None):
    """Create comprehensive daily brief for a specific date"""
    
    if target_date is None:
        target_date = datetime.now()
    
    day_name = target_date.strftime("%A, %B %d, %Y")
    
    # Load intelligence (use current for all dates since this is planning ahead)
    priorities = load_priorities()
    relationships = load_relationships()
    
    # Get calendar for specific date
    calendar = get_calendar_for_date(target_date)
    emails = get_recent_emails()  # Always get recent emails
    
    # Analyze power hour opportunity for this date
    power_hour = analyze_power_hour_opportunity(priorities, calendar, emails, target_date)
    
    brief = f"""# Daily Strategic Brief - {day_name}

## POWER HOUR RECOMMENDATION (6-7 AM MT)

**TODAY'S HIGH-LEVERAGE ACTIVITY:**
**{power_hour['activity']}**

**WHY:** {power_hour['rationale']}

**LEVERAGE:** {power_hour['leverage']}

---

## QUARTERLY ROCKS PROGRESS

### 1. Funding Progress: $250K by March 31
- **Secured:** $50K (DONE)
- **Gap:** $200K remaining
- **Active Sources:** KC Tolliver (investor/VIP), Joe Gilmore & Marc King (considering $100K+)
- **TODAY'S ACTION:** Review any funding-related communications

### 2. Enterprise Deals: $25K MRR
- **Targets:** Floyd's, MAC/MSP, Uber Freight
- **TODAY'S ACTION:** Check for progress on enterprise pipeline

### 3. Real Estate Edition: $50K MRR
- **Partners:** Joe Gilmore (70 clients), Diana Weir/Colibri (luxury real estate)
- **TODAY'S ACTION:** Review RE Edition development status

---

## CURRENT SPRINT STATUS

### Sprint Tasks (Feb 15-28)
- [ ] **Real Estate Webinar:** Schedule for Joe's 70 clients
- [ ] **Colibri Support:** Marketing plan assets and activities
- [ ] **Enterprise Pipeline:** Move 3 deals forward (Moroccanoil, Clorox, Resideo/Honeywell, Uber Freight)
- [ ] **Multi-Site Pipeline:** Move 3 deals forward (Young Life, Focus Financial, Floyd's)

---

## HOT OPPORTUNITIES (Don't Let Slip)

- **Christine @ Moroccanoil** - Enterprise deal needing follow-up
- **Brian Wachtler @ Haberman** - Big agency prospect
- **Brandon @ Atlas Rose** - Agency prospect
- **Floyd's** - Schedule Denver in-person meeting (OVERDUE - next 2 weeks)

---

## TODAY'S CALENDAR

{calendar}

---

## RECENT EMAIL INTELLIGENCE

{emails}

---

## RELATIONSHIP INTELLIGENCE

Check BUSINESS-RELATIONSHIPS.md for latest network updates.
New relationship questions may arrive at 4:30 AM if new contacts detected.

---

## TODAY'S SUCCESS METRICS

**End of day check:**
- [ ] Power Hour completed (6-7 AM)
- [ ] Sprint tasks advanced
- [ ] Hot opportunities contacted
- [ ] Rock progress measured
- [ ] Calendar commitments met

**Remember:** ONE thing that makes everything else easier or unnecessary.

---
*Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} MT*
"""
    
    return brief

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

def create_weekly_strategic_summary():
    """Create weekly strategic summary focused on prep work and time blocks"""
    
    today = datetime.now()
    next_5_days = get_business_dates(today + timedelta(days=1), 5)
    
    summary = f"""# Weekly Strategic Summary & Prep Guide

**Next 5 Business Days:** {next_5_days[0].strftime('%b %d')} - {next_5_days[-1].strftime('%b %d, %Y')}

## QUARTERLY ROCKS STATUS

### 1. Funding Progress: $250K by March 31
- **Secured:** $50K (DONE)
- **Gap:** $200K remaining
- **THIS WEEK'S FOCUS:** KC Tolliver proposal + Joe Gilmore/Marc King follow-up
- **PREP NEEDED:** Investment deck, financial projections, partnership terms

### 2. Enterprise MRR: $25K Goal
- **Active Pipeline:** Floyd's (Denver meeting), MAC/MSP, Uber Freight
- **THIS WEEK'S FOCUS:** Move 3 enterprise deals forward
- **PREP NEEDED:** Custom proposals, enterprise onboarding process, pricing models

### 3. Real Estate Edition: $50K MRR
- **Key Partners:** Joe Gilmore (70 clients), Diana Weir/Colibri (luxury market)
- **THIS WEEK'S FOCUS:** Webinar scheduling, Colibri marketing assets
- **PREP NEEDED:** Demo refinement, marketing collateral, webinar content

---

## BIG ITEMS REQUIRING PREP & TIME BLOCKS

### HIGH-IMPACT PROJECTS (2-4 Hour Blocks)

**1. KC Tolliver Investment Proposal**
- **Why:** $200K funding gap closer
- **Time Block:** 4 hours for research + document creation
- **Prep:** Financial data, growth projections, use of funds breakdown

**2. Real Estate Edition Webinar for Joe's 70 Clients**
- **Why:** Direct path to $50K MRR goal
- **Time Block:** 3 hours for content + platform setup  
- **Prep:** Demo perfection, signup system, follow-up sequence

**3. Enterprise Onboarding Process Design**
- **Why:** Accelerates all 3 enterprise deals simultaneously
- **Time Block:** 2-3 hours for system design
- **Prep:** Current client analysis, bottleneck identification, template creation

**4. Floyd's Denver In-Person Meeting Prep**
- **Why:** Convert enterprise prospect to signed deal
- **Time Block:** 2 hours for meeting design + materials
- **Prep:** Agenda creation, case studies, contract terms, travel logistics

### SPRINT EXECUTION (1-2 Hour Blocks)

**5. Colibri Marketing Assets**
- **Why:** Enable April luxury real estate launch
- **Time Block:** 1-2 hours for asset creation
- **Prep:** Brand guidelines, target audience research, Diana's requirements

**6. Multi-Site Pilot Program Framework**
- **Why:** Standardizes approach for Young Life, Focus Financial, Floyd's
- **Time Block:** 1-2 hours for framework design
- **Prep:** Previous pilot analysis, success metrics definition

---

## RECOMMENDED WEEKLY TIME BLOCKS

### Monday - Strategic Foundation
- **Power Hour:** KC Tolliver Investment Proposal (research phase)
- **Morning Block (2h):** Enterprise onboarding process design
- **Afternoon:** Routine meetings and communications

### Tuesday - Revenue Engine 
- **Power Hour:** Real Estate Edition demo refinement  
- **Morning Block (3h):** Webinar content creation for Joe's 70 clients
- **Afternoon:** Colibri marketing asset creation

### Wednesday - Enterprise Focus
- **Power Hour:** Floyd's meeting agenda and materials
- **Morning Block (2h):** Enterprise proposals (Moroccanoil, Clorox, Resideo)
- **Afternoon:** Multi-site pilot framework

### Thursday - Implementation  
- **Power Hour:** Systems and process refinement
- **Morning:** Execute on prep work from earlier in week
- **Afternoon:** Follow-ups and relationship building

### Friday - Strategic Review
- **Power Hour:** Next week planning and priority setting
- **Morning:** Sprint review and adjustment
- **Afternoon:** Strategic relationship outreach

---

## HOT OPPORTUNITIES (Don't Let Slip)

### OVERDUE/URGENT
- **Floyd's Denver Meeting:** MUST schedule in next 2 weeks
- **Christine @ Moroccanoil:** Enterprise proposal follow-up needed

### HIGH-VALUE PROSPECTS  
- **Brian Wachtler @ Haberman:** Big agency prospect needs nurturing
- **Brandon @ Atlas Rose:** Agency prospect - stay warm
- **Joe Gilmore & Marc King:** $100K+ investment opportunity

---

## POWER HOUR THEME FOR THE WEEK

**Monday-Wednesday:** Revenue Generation Focus
**Thursday-Friday:** Systems & Strategic Planning

**Success Metric:** Each power hour should unlock multiple downstream benefits or eliminate multiple smaller tasks.

---
*Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} MT*
"""
    
    return summary

def cleanup_google_drive_briefings():
    """Clean up old briefing files from Google Drive"""
    try:
        # Run the dedicated cleanup script
        result = subprocess.run([
            'python3', 'cleanup-old-briefings.py'
        ], capture_output=True, text=True, cwd=os.getcwd())
        
        if result.returncode == 0:
            print("🗑️ Google Drive cleanup completed")
            if result.stdout:
                print(result.stdout.split('\n')[-2])  # Show summary line
        else:
            print(f"Drive cleanup warning: {result.stderr}")
        
    except Exception as e:
        print(f"Drive cleanup skipped: {e}")

def main():
    """Run the strategic briefing system"""
    
    print("Creating Strategic Brief System...")
    
    # Clean up old Google Drive files
    cleanup_google_drive_briefings()
    
    # Create daily briefs for next 5 business days
    today = datetime.now()
    next_business_days = get_business_dates(today + timedelta(days=1), 5)
    
    created_files = []
    
    for target_date in next_business_days:
        daily_brief = create_daily_strategic_brief(target_date)
        daily_filename = f"daily-strategic-brief-{target_date.strftime('%Y-%m-%d')}.md"
        
        with open(daily_filename, 'w') as f:
            f.write(daily_brief)
        print(f"✅ Created: {daily_filename}")
        created_files.append(daily_filename)
    
    # Create weekly summary focused on prep work
    weekly_summary = create_weekly_strategic_summary()
    weekly_filename = f"weekly-prep-guide-{datetime.now().strftime('%Y-%m-%d')}.md"
    
    with open(weekly_filename, 'w') as f:
        f.write(weekly_summary)
    print(f"✅ Created: {weekly_filename}")
    created_files.append(weekly_filename)
    
    # Upload all files to Google Drive (Meeting Intelligence folder)
    try:
        meeting_intel_folder_id = "1JI4MHFm8zrm0-eWcV6UXwxdtewC97xH1"  # Meeting Intelligence folder
        
        for filename in created_files:
            subprocess.run([
                'bash', '-c',
                f'source ~/.gog_env && gog drive upload "{filename}" --parent "{meeting_intel_folder_id}" --account keith@atomicelevator.com'
            ])
        
        print(f"☁️ Uploaded {len(created_files)} files to Meeting Intelligence folder")
    except Exception as e:
        print(f"⚠️ Google Drive upload skipped: {e}")
    
    return created_files

if __name__ == "__main__":
    files = main()
    print(f"\n📋 Strategic briefing system complete!")
    for f in files:
        print(f"   • {f}")