#!/usr/bin/env python3
"""
YouTube Clawdbot Intel Scanner - Uses YouTube Data API v3
No cookies needed, no bot detection issues
"""

import os
import json
import requests
from datetime import datetime

# Load API key
with open('/root/.clawdbot/google-api-key.json', 'r') as f:
    API_KEY = json.load(f).get('api_key')

BASE_URL = "https://www.googleapis.com/youtube/v3"

def search_videos(query, max_results=10):
    """Search YouTube for videos matching query"""
    url = f"{BASE_URL}/search"
    params = {
        'part': 'snippet',
        'q': query,
        'type': 'video',
        'maxResults': max_results,
        'order': 'relevance',
        'key': API_KEY
    }
    response = requests.get(url, params=params)
    if response.status_code == 200:
        return response.json().get('items', [])
    else:
        print(f"Error: {response.status_code} - {response.text}")
        return []

def get_video_details(video_id):
    """Get detailed info about a video"""
    url = f"{BASE_URL}/videos"
    params = {
        'part': 'snippet,statistics,contentDetails',
        'id': video_id,
        'key': API_KEY
    }
    response = requests.get(url, params=params)
    if response.status_code == 200:
        items = response.json().get('items', [])
        return items[0] if items else None
    return None

def get_captions(video_id):
    """Get available captions for a video"""
    url = f"{BASE_URL}/captions"
    params = {
        'part': 'snippet',
        'videoId': video_id,
        'key': API_KEY
    }
    response = requests.get(url, params=params)
    if response.status_code == 200:
        return response.json().get('items', [])
    return []

def scan_clawdbot_videos():
    """Main scanner function"""
    queries = [
        "clawdbot tutorial",
        "clawdbot setup guide",
        "clawdbot tips tricks",
        "Alex Finn clawdbot",
        "openclaw tutorial",
        "moltbot setup"
    ]
    
    all_videos = []
    seen_ids = set()
    
    print("🔍 Scanning YouTube for Clawdbot content...\n")
    
    for query in queries:
        print(f"Searching: {query}")
        videos = search_videos(query, max_results=5)
        
        for v in videos:
            vid_id = v['id']['videoId']
            if vid_id not in seen_ids:
                seen_ids.add(vid_id)
                snippet = v['snippet']
                all_videos.append({
                    'id': vid_id,
                    'title': snippet['title'],
                    'channel': snippet['channelTitle'],
                    'description': snippet['description'][:500],
                    'published': snippet['publishedAt'],
                    'url': f"https://youtube.com/watch?v={vid_id}"
                })
    
    print(f"\n✅ Found {len(all_videos)} unique videos\n")
    
    # Generate report
    report = f"""# YouTube Clawdbot Intel Report
**Generated:** {datetime.now().strftime('%Y-%m-%d %H:%M')}
**Videos Found:** {len(all_videos)}

---

"""
    
    for i, v in enumerate(all_videos, 1):
        report += f"""## {i}. {v['title']}
- **Channel:** {v['channel']}
- **Published:** {v['published'][:10]}
- **URL:** {v['url']}
- **Description:** {v['description'][:300]}...

---

"""
    
    # Save report
    output_path = '/home/ccuser/rateright-growth/rivet/memory/plans/youtube-api-scan.md'
    with open(output_path, 'w') as f:
        f.write(report)
    
    print(f"📄 Report saved to: {output_path}")
    return all_videos

if __name__ == "__main__":
    scan_clawdbot_videos()
