#!/usr/bin/env python3
"""
Export Chrome cookies to Netscape format for yt-dlp.
Works even when Chrome is running by copying the database first.

Usage:
  python export_cookies.py [output_file] [domain_filter]

Examples:
  python export_cookies.py /tmp/cookies.txt
  python export_cookies.py /tmp/cookies.txt .youtube.com
"""

import sys
import os
import json
import shutil
import tempfile
import sqlite3
from pathlib import Path
from datetime import datetime

# Chrome paths for different platforms
CHROME_PATHS = {
    'windows': Path('/mnt/c/Users/Rampage/AppData/Local/Google/Chrome/User Data/Default/Network/Cookies'),
    'linux': Path.home() / '.config/google-chrome/Default/Network/Cookies',
}

def export_cookies(output_file: str, domain_filter: str = None) -> dict:
    """Export Chrome cookies to Netscape format"""

    # Find Chrome cookie database
    cookie_db = None
    for platform, path in CHROME_PATHS.items():
        if path.exists():
            cookie_db = path
            break

    if not cookie_db:
        return {'success': False, 'error': 'Chrome cookie database not found'}

    # Create temp copy to avoid lock issues
    with tempfile.NamedTemporaryFile(delete=False, suffix='.db') as tmp:
        tmp_path = tmp.name

    try:
        # Try to copy the database
        try:
            # Use sqlite backup for locked databases
            src_conn = sqlite3.connect(f'file:{cookie_db}?mode=ro&nolock=1', uri=True)
            dst_conn = sqlite3.connect(tmp_path)
            src_conn.backup(dst_conn)
            src_conn.close()
            dst_conn.close()
        except Exception:
            # Fallback: direct copy (may fail if Chrome is running)
            shutil.copy2(cookie_db, tmp_path)

        # Read cookies from the copy
        conn = sqlite3.connect(tmp_path)
        cursor = conn.cursor()

        # Chrome cookie database schema
        query = """
            SELECT host_key, name, encrypted_value, value, path,
                   expires_utc, is_secure, is_httponly
            FROM cookies
        """
        if domain_filter:
            query += f" WHERE host_key LIKE '%{domain_filter}%'"

        cursor.execute(query)
        rows = cursor.fetchall()
        conn.close()

        # Write Netscape format
        with open(output_file, 'w') as f:
            f.write("# Netscape HTTP Cookie File\n")
            f.write("# Exported by Grabbit\n\n")

            count = 0
            for row in rows:
                host_key, name, encrypted_value, value, path, expires_utc, is_secure, is_httponly = row

                # Skip encrypted cookies we can't decode
                if not value and encrypted_value:
                    continue

                # Convert Chrome timestamp (microseconds since 1601) to Unix timestamp
                if expires_utc and expires_utc > 0:
                    # Chrome uses microseconds since Jan 1, 1601
                    # Convert to Unix timestamp (seconds since Jan 1, 1970)
                    expires = int((expires_utc / 1000000) - 11644473600)
                else:
                    expires = 0

                # Netscape format: domain, include_subdomains, path, secure, expires, name, value
                include_subdomains = 'TRUE' if host_key.startswith('.') else 'FALSE'
                secure = 'TRUE' if is_secure else 'FALSE'

                f.write(f"{host_key}\t{include_subdomains}\t{path}\t{secure}\t{expires}\t{name}\t{value}\n")
                count += 1

        return {
            'success': True,
            'output_file': output_file,
            'cookie_count': count,
            'source': str(cookie_db)
        }

    except Exception as e:
        return {'success': False, 'error': str(e)}
    finally:
        # Clean up temp file
        try:
            os.unlink(tmp_path)
        except:
            pass


def main():
    output_file = sys.argv[1] if len(sys.argv) > 1 else '/tmp/grabbit_cookies.txt'
    domain_filter = sys.argv[2] if len(sys.argv) > 2 else None

    result = export_cookies(output_file, domain_filter)
    print(json.dumps(result))
    sys.exit(0 if result['success'] else 1)


if __name__ == '__main__':
    main()
