#!/usr/bin/env python3
"""
Subprocess wrapper for FastDL operations to avoid asyncio event loop conflicts.
This runs FastDL operations in a completely isolated subprocess.

Supports both single content_type (backward compatible) and multi content_types mode.
"""

import sys
import json
from pathlib import Path

# Add parent directory to path
sys.path.insert(0, str(Path(__file__).parent.parent))

from wrappers.base_subprocess_wrapper import create_download_wrapper, create_download_wrapper_multi


def create_fastdl_downloader(config, unified_db):
    """Factory function to create a FastDL downloader instance."""
    from modules.fastdl_module import FastDLDownloader

    # When defer_database is set (paid content mode), skip FastDL's own dedup
    # checks — the caller handles dedup via its own known_ids filtering.
    use_db = not config.get('defer_database', False)

    return FastDLDownloader(
        headless=config.get('headless', True),
        show_progress=True,
        use_database=use_db,
        log_callback=None,  # Module uses universal logger, no callback needed
        unified_db=unified_db,
        high_res=config.get('high_res', False)
    )


# Create download functions using the factories
run_fastdl_download = create_download_wrapper("FastDL", "fastdl", create_fastdl_downloader)
run_fastdl_download_multi = create_download_wrapper_multi("FastDL", "fastdl", create_fastdl_downloader)


if __name__ == '__main__':
    config_json = sys.stdin.read()
    config = json.loads(config_json)

    if 'content_types' in config:
        result = run_fastdl_download_multi(config)
    else:
        result = run_fastdl_download(config)

    print(json.dumps(result))
    sys.exit(0 if result.get('status') == 'success' else 1)
