#!/usr/bin/env python3
"""
Study Planner for Xavier
Track study sessions, time, and progress
"""

import argparse
import json
import os
from datetime import datetime, timedelta
from pathlib import Path

# Data directory
DATA_DIR = Path(__file__).parent.parent / "data"
DATA_DIR.mkdir(exist_ok=True)

LOG_FILE = DATA_DIR / "study-log.json"
GOALS_FILE = DATA_DIR / "weekly-goals.json"

def load_log() -> list:
    """Load study session log"""
    if LOG_FILE.exists():
        with open(LOG_FILE) as f:
            return json.load(f)
    return []

def save_log(log: list):
    """Save study session log"""
    with open(LOG_FILE, "w") as f:
        json.dump(log, f, indent=2)

def start_session(subject: str, goal: str):
    """Start a new study session"""
    log = load_log()
    
    # Check for unclosed sessions
    for entry in log:
        if entry.get("end_time") is None:
            print(f"⚠️  You have an open session for {entry['subject']}!")
            print(f"   Started at {entry['start_time']}")
            print(f"   Run: study.py end --notes 'your notes' first")
            return
    
    session = {
        "id": len(log) + 1,
        "subject": subject,
        "goal": goal,
        "start_time": datetime.now().isoformat(),
        "end_time": None,
        "notes": None,
        "duration_minutes": None
    }
    
    log.append(session)
    save_log(log)
    
    print(f"📚 Study session started!")
    print(f"   Subject: {subject}")
    print(f"   Goal: {goal}")
    print(f"   Time: {datetime.now().strftime('%I:%M %p')}")
    print(f"\n💡 Remember: 25 min focus, then 5 min break!")
    print(f"   When done, run: study.py end --notes 'what you accomplished'")

def end_session(notes: str):
    """End the current study session"""
    log = load_log()
    
    # Find open session
    for entry in reversed(log):
        if entry.get("end_time") is None:
            end_time = datetime.now()
            start_time = datetime.fromisoformat(entry["start_time"])
            duration = (end_time - start_time).total_seconds() / 60
            
            entry["end_time"] = end_time.isoformat()
            entry["notes"] = notes
            entry["duration_minutes"] = round(duration, 1)
            
            save_log(log)
            
            print(f"✅ Study session completed!")
            print(f"   Subject: {entry['subject']}")
            print(f"   Duration: {int(duration)} minutes")
            print(f"   Notes: {notes}")
            
            if duration >= 25:
                print(f"\n🎉 Great job staying focused!")
            
            return
    
    print("⚠️  No open study session found.")
    print("   Start one with: study.py start --subject 'Math' --goal 'your goal'")

def show_summary(period: str = "week"):
    """Show study summary"""
    log = load_log()
    
    if not log:
        print("📊 No study sessions recorded yet.")
        print("   Start one with: study.py start --subject 'Math' --goal 'your goal'")
        return
    
    # Filter by period
    now = datetime.now()
    if period == "week":
        start_of_week = now - timedelta(days=now.weekday())
        start_of_week = start_of_week.replace(hour=0, minute=0, second=0, microsecond=0)
    elif period == "today":
        start_of_week = now.replace(hour=0, minute=0, second=0, microsecond=0)
    else:
        start_of_week = now - timedelta(days=30)
    
    filtered = [
        e for e in log 
        if e.get("end_time") and datetime.fromisoformat(e["start_time"]) >= start_of_week
    ]
    
    if not filtered:
        print(f"📊 No completed sessions this {period}.")
        return
    
    # Calculate stats
    by_subject = {}
    total_minutes = 0
    
    for entry in filtered:
        subject = entry["subject"]
        duration = entry.get("duration_minutes", 0)
        
        if subject not in by_subject:
            by_subject[subject] = {"sessions": 0, "minutes": 0}
        
        by_subject[subject]["sessions"] += 1
        by_subject[subject]["minutes"] += duration
        total_minutes += duration
    
    # Display
    print(f"📊 Study Summary ({period.title()})")
    print("=" * 40)
    
    for subject, stats in sorted(by_subject.items(), key=lambda x: -x[1]["minutes"]):
        hours = stats["minutes"] / 60
        print(f"   {subject}: {stats['sessions']} sessions, {hours:.1f} hours")
    
    print("=" * 40)
    print(f"   Total: {total_minutes / 60:.1f} hours")
    
    # Recommendations
    weak_subjects = ["Business", "Constitution"]  # From grade analysis
    studied_subjects = set(by_subject.keys())
    missing = [s for s in weak_subjects if s not in studied_subjects]
    
    if missing:
        print(f"\n💡 Don't forget to study: {', '.join(missing)}")

def main():
    parser = argparse.ArgumentParser(description="Study session tracker")
    subparsers = parser.add_subparsers(dest="command")
    
    # Start session
    start_parser = subparsers.add_parser("start", help="Start a study session")
    start_parser.add_argument("--subject", required=True, help="Subject to study")
    start_parser.add_argument("--goal", required=True, help="Goal for this session")
    
    # End session
    end_parser = subparsers.add_parser("end", help="End current session")
    end_parser.add_argument("--notes", required=True, help="What you accomplished")
    
    # Summary
    summary_parser = subparsers.add_parser("summary", help="View study summary")
    summary_parser.add_argument("--week", action="store_true", help="This week")
    summary_parser.add_argument("--today", action="store_true", help="Today only")
    
    args = parser.parse_args()
    
    if args.command == "start":
        start_session(args.subject, args.goal)
    elif args.command == "end":
        end_session(args.notes)
    elif args.command == "summary":
        period = "today" if args.today else "week"
        show_summary(period)
    else:
        parser.print_help()

if __name__ == "__main__":
    main()
