#!/usr/bin/env python3
"""
Genesis NotebookLM Skill
========================
Simulates NotebookLM's deep research capabilities by synthesizing 
multi-source data through Gemini 2.0 with search grounding.

Features:
- Source synthesis (Web + Local)
- Deep research summaries
- Data table generation
- Citation tracking

Usage:
    from notebook_lm_skill import NotebookLMAgent
    agent = NotebookLMAgent()
    result = agent.deep_research("The future of agentic AI in 2026")
"""

import os
import sys
import json
from datetime import datetime
from typing import List, Dict, Any, Optional

# Add genesis-system to path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from search_grounding import SearchGroundedAgent
from budget_manager import BudgetManager

class NotebookLMAgent:
    """
    Agent that mimics NotebookLM's synthesis capabilities.
    Uses grounded search to gather data and a large context window 
    to synthesize it into structured intelligence.
    """
    
    def __init__(self, budget_limit: float = 10.0):
        self.grounded_agent = SearchGroundedAgent(budget_limit=budget_limit)
        self.budget = BudgetManager(daily_limit=budget_limit)
        
        print(f"[OK] NotebookLM Skill Initialized")
    
    def deep_research(self, topic: str, depth: int = 4) -> Dict[str, Any]:
        """
        Perform a deep dive research into a topic.
        """
        print(f"[NOTEBOOK] Starting deep research on: {topic}")
        
        # 1. Gather raw grounded data
        research_result = self.grounded_agent.research(topic, depth=depth)
        
        # 2. Synthesize into a "Source Notebook"
        sources = research_result.get("findings", [])
        citations = research_result.get("citations", [])
        
        # 3. Generate structured "Study Guide" / "Intelligence Report"
        synthesis_prompt = f"""You are the Genesis NotebookLM Synthesis Engine.
You have been provided with the following raw research findings on the topic: '{topic}'

RAW FINDINGS:
{json.dumps(sources, indent=2)}

CITATIONS:
{json.dumps(citations, indent=2)}

TASK:
1. Synthesize these findings into a comprehensive "Intelligence Report".
2. Create a "Data Table" representing the key metrics or entities found.
3. Identify "Critical Insights" and "Future Trajectories".
4. Maintain strict factual grounding based ONLY on the findings.

Format the output in clear Markdown."""

        final_synthesis = self.grounded_agent.query(synthesis_prompt, use_grounding=False)
        
        return {
            "topic": topic,
            "report": final_synthesis["response"],
            "sources_count": len(sources),
            "citations": citations,
            "cost": research_result["total_cost"] + final_synthesis["cost"],
            "timestamp": datetime.now().isoformat()
        }

    def generate_data_table(self, data_points: List[str], focus: str) -> str:
        """
        Mimic NotebookLM's data table feature.
        """
        prompt = f"Convert the following data points into a structured Markdown table focusing on {focus}:\n\n" + "\n".join(data_points)
        result = self.grounded_agent.query(prompt, use_grounding=False)
        return result["response"]

# CLI for testing
if __name__ == "__main__":
    import argparse
    
    parser = argparse.ArgumentParser(description="NotebookLM Skill")
    parser.add_argument("--research", "-r", type=str, help="Research topic")
    parser.add_argument("--test", action="store_true", help="Run self-test")
    args = parser.parse_args()
    
    agent = NotebookLMAgent()
    
    if args.test:
        print("\n[TEST] NotebookLM Skill Self-Test")
        # Minor test
        print(f"[OK] Agent ready. Testing table generation...")
        table = agent.generate_data_table(["Item 1: $10", "Item 2: $20"], "Pricing")
        print(table)
        print("\n[DONE] Self-test complete")
        
    elif args.research:
        result = agent.deep_research(args.research)
        print(f"\n--- INTELLIGENCE REPORT: {result['topic']} ---")
        print(result["report"])
        print(f"\n[SOURCES] {result['sources_count']} sources synthesized.")
        print(f"[COST] ${result['cost']:.4f}")
    else:
        print("Usage: python notebook_lm_skill.py --research 'topic'")
