#!/usr/bin/env python3
"""
ADHD-Friendly Daily Planner
Task management optimized for ADHD working styles
"""

import json
import os
import sys
from datetime import datetime, timedelta
from enum import Enum


class Energy(Enum):
    """Task energy requirement"""
    HYPER = "hyper"      # High energy, fast-paced
    HIGH = "high"        # Focused, demanding
    MEDIUM = "medium"    # Moderate focus
    LOW = "low"          # Minimal energy
    IDLE = "idle"        # Can do on autopilot


class Task:
    """ADHD-friendly task"""
    
    def __init__(self, title: str, duration_min: int, energy: str, completed: bool = False):
        self.title = title
        self.duration_min = duration_min
        self.energy = energy
        self.completed = completed
        self.created_at = datetime.now().isoformat()
    
    def to_dict(self) -> dict:
        return {
            "title": self.title,
            "duration_min": self.duration_min,
            "energy": self.energy,
            "completed": self.completed,
            "created_at": self.created_at
        }


class DailyPlan:
    """ADHD-aware daily plan"""
    
    def __init__(self):
        self.tasks = []
        self.energy_level = "medium"
        self.created_at = datetime.now().isoformat()
    
    def add_task(self, title: str, duration_min: int, energy: str) -> None:
        """Add a task (no guilt if not completed)"""
        if duration_min > 60:
            print(f"⚠️  Task '{title}' is {duration_min}min. Consider breaking into smaller pieces.")
        
        task = Task(title, duration_min, energy)
        self.tasks.append(task)
    
    def suggest_order(self, current_energy: str = "medium") -> list:
        """
        Suggest task order based on energy level and context switching
        
        Algorithm:
        - Group by energy level (minimize context switching)
        - Start with matching current energy
        - Use low-energy tasks for afternoon slump
        """
        
        energy_order = {
            "hyper": 0,
            "high": 1,
            "medium": 2,
            "low": 3,
            "idle": 4
        }
        
        current_level = energy_order.get(current_energy, 2)
        
        # Sort by proximity to current energy, then by duration (shorter first)
        suggested = sorted(
            [t for t in self.tasks if not t.completed],
            key=lambda t: (
                abs(energy_order.get(t.energy, 2) - current_level),  # Closest energy
                t.duration_min  # Shorter tasks first (momentum)
            )
        )
        
        return suggested
    
    def estimate_daily_load(self) -> dict:
        """Estimate if today is realistic"""
        total_time = sum(t.duration_min for t in self.tasks if not t.completed)
        
        # ADHD reality: productivity is ~4-6 hours effective time
        effective_hours = 5  # Conservative estimate
        effective_minutes = effective_hours * 60
        
        return {
            "total_time_min": total_time,
            "effective_hours": effective_hours,
            "realistic": total_time <= effective_minutes,
            "ratio": f"{total_time}/{effective_minutes}",
            "message": (
                "✅ Realistic!" if total_time <= effective_minutes 
                else f"⚠️  That's {total_time - effective_minutes}min over. Consider dropping or rescheduling tasks."
            )
        }
    
    def get_dopamine_hits(self) -> list:
        """Show quick wins to maintain motivation"""
        quick_wins = [t for t in self.tasks if not t.completed and t.duration_min <= 15]
        return quick_wins
    
    def create_schedule(self) -> list:
        """
        Create a flexible time-block schedule
        Includes buffers, break reminders, context groups
        """
        
        suggested = self.suggest_order()
        schedule = []
        
        current_time = datetime.now().replace(hour=9, minute=0)  # Start at 9 AM
        
        for i, task in enumerate(suggested):
            # Add buffer before switch (not before first task)
            if i > 0 and task.energy != suggested[i-1].energy:
                schedule.append({
                    "type": "context_switch",
                    "duration": 5,
                    "note": f"Breathe, stretch, switch gears"
                })
                current_time += timedelta(minutes=5)
            
            # Add the task
            schedule.append({
                "time": current_time.strftime("%H:%M"),
                "task": task.title,
                "duration_min": task.duration_min,
                "energy_level": task.energy
            })
            current_time += timedelta(minutes=task.duration_min)
            
            # Add break after 90min focus
            total_elapsed = sum(1 for t in schedule if t.get("type") != "break") * 10  # Rough estimate
            if total_elapsed > 90:
                schedule.append({
                    "type": "break",
                    "duration": 15,
                    "note": "Move, hydrate, reset"
                })
                current_time += timedelta(minutes=15)
        
        return schedule
    
    def to_dict(self) -> dict:
        return {
            "created_at": self.created_at,
            "tasks": [t.to_dict() for t in self.tasks],
            "task_count": len(self.tasks),
            "completed_count": sum(1 for t in self.tasks if t.completed)
        }


def main():
    if len(sys.argv) < 2:
        print("ADHD-Friendly Daily Planner")
        print("Usage: adhd-daily-planner [--today] [--add TASK MIN ENERGY] [--suggest] [--schedule]")
        return
    
    plan = DailyPlan()
    
    # Parse arguments
    i = 1
    while i < len(sys.argv):
        arg = sys.argv[i]
        
        if arg == "--add" and i + 3 < len(sys.argv):
            task_title = sys.argv[i + 1]
            duration = int(sys.argv[i + 2])
            energy = sys.argv[i + 3]
            plan.add_task(task_title, duration, energy)
            i += 4
        
        elif arg == "--suggest":
            print("\n📋 Suggested Task Order:")
            suggested = plan.suggest_order()
            for j, task in enumerate(suggested, 1):
                print(f"  {j}. {task.title} ({task.duration_min}min, {task.energy})")
            i += 1
        
        elif arg == "--estimate":
            print("\n⏱️  Daily Load Estimate:")
            est = plan.estimate_daily_load()
            print(f"  {est['message']}")
            print(f"  Time: {est['ratio']} minutes")
            i += 1
        
        elif arg == "--dopamine":
            print("\n🎯 Quick Wins (momentum builders):")
            wins = plan.get_dopamine_hits()
            if wins:
                for task in wins:
                    print(f"  ✨ {task.title} ({task.duration_min}min)")
            else:
                print("  (No quick wins yet. Add some!)")
            i += 1
        
        elif arg == "--schedule":
            print("\n📅 Today's Schedule (Flexible):")
            schedule = plan.create_schedule()
            for item in schedule:
                if item.get("type") == "break":
                    print(f"  ☕ BREAK: {item['note']} ({item['duration']}min)")
                elif item.get("type") == "context_switch":
                    print(f"  ⚡ {item['note']} ({item['duration']}min)")
                else:
                    print(f"  {item['time']} - {item['task']} ({item['duration_min']}min)")
            i += 1
        
        else:
            i += 1
    
    if len(sys.argv) == 2 and sys.argv[1] == "--today":
        print("Plan created. Use --add, --suggest, --schedule, --estimate, --dopamine")


if __name__ == "__main__":
    main()
