#!/usr/bin/env python3
import os
import sys
import subprocess
import json
from datetime import datetime
from internetarchive import upload, get_item

def download_twitch_video(video_url, output_dir="downloads"):
    """Download Twitch video using yt-dlp"""
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    
    # Get video info first
    info_cmd = [
        "yt-dlp",
        "--dump-json",
        video_url
    ]
    
    try:
        result = subprocess.run(info_cmd, capture_output=True, text=True, check=True)
        video_info = json.loads(result.stdout)
        
        # Extract metadata
        video_id = video_info.get('id', 'unknown')
        title = video_info.get('title', 'Untitled')
        uploader = video_info.get('uploader', 'Unknown')
        upload_date = video_info.get('upload_date', '')
        description = video_info.get('description', '')
        
        # Download video
        output_template = os.path.join(output_dir, f"{video_id}_%(title)s.%(ext)s")
        download_cmd = [
            "yt-dlp",
            "-o", output_template,
            "--write-info-json",
            "--write-thumbnail",
            video_url
        ]
        
        print(f"Downloading: {title}")
        subprocess.run(download_cmd, check=True)
        
        # Find downloaded file
        video_file = None
        for file in os.listdir(output_dir):
            if file.startswith(video_id) and not file.endswith(('.json', '.jpg', '.png', '.webp')):
                video_file = os.path.join(output_dir, file)
                break
        
        if not video_file:
            raise Exception("Downloaded video file not found")
        
        return {
            'file_path': video_file,
            'video_id': video_id,
            'title': title,
            'uploader': uploader,
            'upload_date': upload_date,
            'description': description,
            'url': video_url
        }
        
    except subprocess.CalledProcessError as e:
        print(f"Error downloading video: {e}")
        return None

def upload_to_archive(video_data, collection='opensource_movies'):
    """Upload video to Internet Archive"""
    
    # Create identifier (must be unique)
    identifier = f"twitch-{video_data['uploader']}-{video_data['video_id']}"
    identifier = identifier.lower().replace(' ', '-').replace('_', '-')
    
    # Prepare metadata
    metadata = {
        'title': f"{video_data['title']}",
        'creator': video_data['uploader'],
        'date': video_data['upload_date'][:4] if video_data['upload_date'] else str(datetime.now().year),
        'subject': ['twitch', 'gaming', 'livestream', 'video game'],
        'mediatype': 'movies',
        'collection': collection,
        'source': video_data['url'],
        'language': 'eng'
    }
    
    # Check if item already exists
    item = get_item(identifier)
    if item.exists:
        print(f"Item {identifier} already exists on Internet Archive")
        return False
    
    print(f"Uploading to Internet Archive with identifier: {identifier}")
    
    try:
        # Upload file
        r = upload(
            identifier,
            files=[video_data['file_path']],
            metadata=metadata,
            verify=True,
            checksum=True
        )
        
        if r[0].status_code == 200:
            print(f"Successfully uploaded: https://archive.org/details/{identifier}")
            return True
        else:
            print(f"Upload failed with status code: {r[0].status_code}")
            return False
            
    except Exception as e:
        print(f"Error uploading to Internet Archive: {e}")
        return False

def archive_twitch_video(video_url, keep_local=False):
    """Main function to archive a Twitch video"""
    
    # Download video
    video_data = download_twitch_video(video_url)
    if not video_data:
        print("Failed to download video")
        return False
    
    # Upload to Internet Archive
    success = upload_to_archive(video_data)
    
    # Clean up local file if requested
    if not keep_local and success:
        try:
            os.remove(video_data['file_path'])
            # Also remove metadata files
            json_file = video_data['file_path'].rsplit('.', 1)[0] + '.info.json'
            if os.path.exists(json_file):
                os.remove(json_file)
            print("Local files cleaned up")
        except Exception as e:
            print(f"Error cleaning up files: {e}")
    
    return success

def main():
    if len(sys.argv) < 2:
        print("Usage: python archive_twitch.py <twitch_video_url> [--keep-local]")
        print("Example: python archive_twitch.py https://www.twitch.tv/videos/123456789")
        sys.exit(1)
    
    video_url = sys.argv[1]
    keep_local = '--keep-local' in sys.argv
    
    # Archive the video
    archive_twitch_video(video_url, keep_local)

if __name__ == "__main__":
    main()

Add function for archiving all videos in channel