#!/usr/bin/env python3
"""
Deep Research Work Tool
Research automation with structured deep work sessions
"""

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


def plan_research_session(topic: str, depth: str = "balanced", duration_minutes: int = 60) -> dict:
    """
    Plan a structured research session
    
    Args:
        topic: Research topic
        depth: "quick" (20min), "balanced" (60min), "comprehensive" (120min)
        duration_minutes: Session duration
    
    Returns:
        Research plan with phases, sources to check, and goals
    """
    
    depths = {
        "quick": {"phases": 3, "per_phase": 6},
        "balanced": {"phases": 5, "per_phase": 12},
        "comprehensive": {"phases": 7, "per_phase": 18}
    }
    
    config = depths.get(depth, depths["balanced"])
    phase_duration = duration_minutes // config["phases"]
    
    plan = {
        "topic": topic,
        "depth": depth,
        "total_duration": duration_minutes,
        "phases": [],
        "sources_to_check": [],
        "synthesis_goal": f"Comprehensive research memo on {topic}",
        "start_time": datetime.now().isoformat(),
        "estimated_end": (datetime.now() + timedelta(minutes=duration_minutes)).isoformat()
    }
    
    phase_names = [
        "Background & Context",
        "Key Sources & Experts",
        "Data & Evidence",
        "Counterarguments",
        "Synthesis & Gaps",
        "Deep Dive",
        "Final Review"
    ]
    
    for i in range(config["phases"]):
        plan["phases"].append({
            "number": i + 1,
            "name": phase_names[i] if i < len(phase_names) else f"Phase {i+1}",
            "duration_minutes": phase_duration,
            "goal": f"Identify {config['per_phase']} key points"
        })
    
    plan["sources_to_check"] = [
        "Academic databases (Google Scholar)",
        "News & journalism archives",
        "Primary sources & research papers",
        "Expert opinions & interviews",
        "Statistics & data repositories"
    ]
    
    return plan


def create_research_workspace(topic: str, workspace_path: str = None) -> str:
    """
    Create a workspace for organizing research materials
    """
    if not workspace_path:
        workspace_path = os.path.expanduser(f"~/Documents/Research-{datetime.now().strftime('%Y%m%d-%H%M')}")
    
    os.makedirs(workspace_path, exist_ok=True)
    
    subdirs = [
        "sources",
        "notes",
        "synthesis",
        "citations"
    ]
    
    for subdir in subdirs:
        os.makedirs(os.path.join(workspace_path, subdir), exist_ok=True)
    
    # Create index file
    index = {
        "topic": topic,
        "created": datetime.now().isoformat(),
        "sources_found": [],
        "key_findings": [],
        "questions_answered": [],
        "follow_up_questions": []
    }
    
    with open(os.path.join(workspace_path, "index.json"), "w") as f:
        json.dump(index, f, indent=2)
    
    return workspace_path


def main():
    if len(sys.argv) < 2:
        topic = "research topic"
        depth = "balanced"
        duration = 60
    else:
        topic = sys.argv[1] if len(sys.argv) > 1 else "research topic"
        depth = sys.argv[2] if len(sys.argv) > 2 else "balanced"
        duration = int(sys.argv[3]) if len(sys.argv) > 3 else 60
    
    print(f"📚 Planning research session: {topic}")
    print(f"   Depth: {depth}, Duration: {duration} minutes\n")
    
    plan = plan_research_session(topic, depth, duration)
    workspace = create_research_workspace(topic)
    
    print(f"✅ Research plan created")
    print(f"✅ Workspace: {workspace}\n")
    
    print("PHASES:")
    for phase in plan["phases"]:
        print(f"  {phase['number']}. {phase['name']} ({phase['duration_minutes']}min)")
    
    print(f"\nSources to check:")
    for source in plan["sources_to_check"]:
        print(f"  • {source}")
    
    print(f"\n💾 Plan saved to {workspace}/index.json")


if __name__ == "__main__":
    main()
