#!/usr/bin/env python3
"""
Upload files to WeTransfer using their API
"""

import requests
import os
import sys
import mimetypes
from pathlib import Path

def upload_to_we_transfer(files):
    """
    Upload files to WeTransfer

    Args:
        files: List of file paths
    """
    # WeTransfer API endpoint
    url = "https://wetransfer.com/api/v4/transfers"

    # Prepare files for upload
    prepared_files = []
    for file_path in files:
        path = Path(file_path)
        if not path.exists():
            print(f"❌ File not found: {file_path}")
            return None

        mime_type, _ = mimetypes.guess_type(file_path)
        if mime_type is None:
            mime_type = 'application/octet-stream'

        prepared_files.append({
            'path': file_path,
            'filename': path.name,
            'content_type': mime_type,
            'size': path.stat().st_size
        })

    # Calculate total size
    total_size = sum(f['size'] for f in prepared_files)
    print(f"📦 Total size: {total_size / (1024*1024):.1f} MB")

    # Create transfer
    try:
        # First, create the transfer with file info
        transfer_data = {
            "data": {
                "type": "multirecipient-upload",
                "total_files": len(prepared_files),
                "total_size": total_size,
                "files": [
                    {
                        "name": f['filename'],
                        "size": f['size'],
                        "content_type": f['content_type']
                    }
                    for f in prepared_files
                ]
            }
        }

        # Create transfer
        response = requests.post(url, json=transfer_data, headers={
            "Content-Type": "application/json",
            "X-Api-Key": "",  # Public API doesn't need key
            "User-Agent": "clawdbot-uploader/1.0"
        }, timeout=30)

        if response.status_code != 200:
            print(f"❌ Failed to create transfer: {response.status_code}")
            print(f"Response: {response.text}")
            return None

        transfer = response.json()['data']
        print(f"✅ Transfer created: {transfer['id']}")

        # Note: WeTransfer's public API requires a specific upload flow
        # with chunked uploads and authorization. For simplicity,
        # let's use a different approach - Transfer.sh or similar

        # Actually, let me use transfer.sh (now known as Transfer.sh or Temp.sh)
        print("\n⚠️ WeTransfer public API requires complex chunked uploads")
        print("📌 Switching to transfer.sh (Transfer.p0int) instead")

        return upload_to_transfer_sh(files)

    except Exception as e:
        print(f"❌ Error: {e}")
        return None


def upload_to_transfer_sh(files):
    """
    Upload files to Transfer.sh (https://transfer.sh/)

    Args:
        files: List of file paths
    """
    url = "https://transfer.sh/"

    total_size = sum(Path(f).stat().st_size for f in files)
    print(f"📤 Uploading to Transfer.sh...")
    print(f"📦 Total size: {total_size / (1024*1024):.1f} MB")

    try:
        # Upload all files in one request
        files_data = {}
        for i, file_path in enumerate(files):
            path = Path(file_path)
            files_data[f'file{i}'] = (path.name, open(file_path, 'rb'))

        response = requests.post(url, files=files_data, timeout=3600)

        for f in files_data.values():
            f[1].close()

        if response.status_code != 200:
            print(f"❌ Upload failed: {response.status_code}")
            print(f"Response: {response.text}")
            return None

        download_url = response.text.strip()
        print(f"\n✅ Upload successful!")
        print(f"🔗 Download link: {download_url}")
        print(f"\n📝 Note: Files will be available for 14 days (default)")
        print(f"🔗 Direct file links may be available at: {download_url}/#")

        return download_url

    except Exception as e:
        print(f"❌ Error: {e}")
        return None


def main():
    if len(sys.argv) < 2:
        print("Usage: we_transfer_uploader.py <file1> [file2] [file3] ...")
        print("\nExample:")
        print("  python3 we_transfer_uploader.py video.mp4 subs1.srt subs2.srt")
        sys.exit(1)

    files = sys.argv[1:]

    # Check if all files exist
    for f in files:
        if not Path(f).exists():
            print(f"❌ File not found: {f}")
            sys.exit(1)

    # Upload to Transfer.sh (simpler than WeTransfer)
    upload_to_transfer_sh(files)


if __name__ == "__main__":
    main()
