#!/usr/bin/env python3
"""
Media Downloader Setup Script
Prepares the application for installation
"""

import json
import os
import sys
from pathlib import Path
import shutil

def create_default_config():
    """Create default configuration file"""
    config = {
        "instagram": {
            "enabled": False,
            "method": "instaloader",
            "username": "",
            "password": "",
            "totp_secret": "",
            "session_file": "sessions/session-username",
            "accounts": [],
            "posts": {
                "enabled": True,
                "days_back": 3,
                "temp_dir": "temp/ig/posts",
                "destination_path": "/path/to/media/instagram/posts",
                "extensions": [".jpg", ".jpeg", ".png", ".heic", ".mp4", ".mov"]
            },
            "stories": {
                "enabled": True,
                "days_back": 3,
                "temp_dir": "temp/ig/stories",
                "destination_path": "/path/to/media/instagram/stories",
                "extensions": [".jpg", ".jpeg", ".png", ".heic", ".mp4", ".mov"]
            },
            "reels": {
                "enabled": True,
                "days_back": 3,
                "temp_dir": "temp/ig/reels",
                "destination_path": "/path/to/media/instagram/reels",
                "extensions": [".jpg", ".jpeg", ".png", ".heic", ".mp4", ".mov"]
            },
            "max_downloads_per_user": 100
        },
        "fastdl": {
            "enabled": True,
            "high_res": False,
            "usernames": [],
            "phrase_search": {
                "enabled": False,
                "usernames": [],
                "phrases": [],
                "case_sensitive": False,
                "match_all": False
            },
            "check_interval_hours": 4,
            "run_at_start": True,
            "posts": {
                "enabled": False,
                "days_back": 3,
                "temp_dir": "temp/fastdl/posts",
                "destination_path": "/path/to/media/instagram/posts"
            },
            "stories": {
                "enabled": True,
                "days_back": 3,
                "temp_dir": "temp/fastdl/stories",
                "destination_path": "/path/to/media/instagram/stories"
            },
            "reels": {
                "enabled": True,
                "days_back": 3,
                "temp_dir": "temp/fastdl/reels",
                "destination_path": "/path/to/media/instagram/reels"
            }
        },
        "imginn": {
            "enabled": True,
            "usernames": [],
            "phrase_search": {
                "enabled": False,
                "usernames": [],
                "phrases": [],
                "case_sensitive": False,
                "match_all": False
            },
            "cookie_file": "cookies/imginn_cookies.json",
            "check_interval_hours": 4,
            "run_at_start": True,
            "posts": {
                "enabled": False,
                "days_back": 3,
                "temp_dir": "temp/imginn/posts",
                "destination_path": "/path/to/media/instagram/posts"
            },
            "stories": {
                "enabled": False,
                "days_back": 3,
                "temp_dir": "temp/imginn/stories",
                "destination_path": "/path/to/media/instagram/stories"
            },
            "tagged": {
                "enabled": True,
                "days_back": 7,
                "temp_dir": "temp/imginn/tagged",
                "destination_path": "/path/to/media/instagram/tagged"
            }
        },
        "toolzu": {
            "enabled": False,
            "usernames": [],
            "email": "",
            "password": "",
            "cookie_file": "cookies/toolzu_cookies.json",
            "check_interval_hours": 4,
            "run_at_start": True,
            "posts": {
                "enabled": False,
                "days_back": 3,
                "temp_dir": "temp/toolzu/posts",
                "destination_path": "/path/to/media/instagram/posts"
            },
            "stories": {
                "enabled": True,
                "days_back": 3,
                "temp_dir": "temp/toolzu/stories",
                "destination_path": "/path/to/media/instagram/stories"
            }
        },
        "snapchat": {
            "enabled": False,
            "check_interval_hours": 4,
            "cookie_file": "cookies/snapchat_cookies.json",
            "usernames": [],
            "run_at_start": True,
            "stories": {
                "enabled": True,
                "days_back": 3,
                "max_downloads": 50,
                "temp_dir": "temp/snapchat/stories",
                "destination_path": "/path/to/media/snapchat/stories"
            }
        },
        "tiktok": {
            "enabled": True,
            "accounts": [],
            "full_profile": False,
            "days_back": 3,
            "temp_dir": "temp/tiktok",
            "destination_path": "/path/to/media/tiktok",
            "extensions": [".mp4", ".webm", ".m4a", ".mp3", ".mov"]
        },
        "forums": {
            "enabled": False,
            "headless": True,
            "configs": []
        },
        "download_settings": {
            "output_dir": "downloads",
            "use_temp_dir": True,
            "move_to_destination": True,
            "rate_limit": 50,
            "min_delay": 5,
            "max_delay": 10,
            "show_debug": False
        },
        "immich": {
            "enabled": False,
            "api_url": "http://localhost:2283/api",
            "api_key": "your-api-key-here",
            "library_id": "",
            "scan_after_download": True,
            "scan_at_end": False
        },
        "pushover": {
            "enabled": False,
            "user_key": "",
            "api_token": "",
            "priority": 0,
            "device": "",
            "include_image": True
        },
        "scheduler": {
            "module_run_order": ["imginn", "fastdl", "toolzu", "snapchat", "tiktok", "forums"]
        }
    }

    return config

def setup():
    """Run setup process"""
    print("Media Downloader Setup")
    print("======================")
    print()

    # Check Python version
    if sys.version_info < (3, 7):
        print("Error: Python 3.7 or higher is required")
        sys.exit(1)

    # Create config directory
    config_dir = Path("config")
    config_dir.mkdir(exist_ok=True)

    config_file = config_dir / "settings.json"

    # Create config if it doesn't exist
    if not config_file.exists():
        print("Creating default configuration...")
        config = create_default_config()

        # Interactive setup
        print("\nQuick Setup (you can edit config/settings.json later)")
        print("=" * 50)

        # Instagram username
        if input("\nConfigure Instagram downloads? (y/n): ").lower() == 'y':
            username = input("Enter Instagram username to download: ").strip()
            if username:
                config["fastdl"]["usernames"] = [username]
                config["imginn"]["usernames"] = [username]

        # TikTok
        if input("\nConfigure TikTok downloads? (y/n): ").lower() == 'y':
            username = input("Enter TikTok username: ").strip()
            if username:
                config["tiktok"]["accounts"] = [{
                    "username": username,
                    "check_interval_hours": 4,
                    "run_at_start": True
                }]

        # Destination paths
        if input("\nSet custom destination paths? (y/n): ").lower() == 'y':
            base_path = input("Enter base media path (e.g., /opt/immich/media): ").strip()
            if base_path:
                # Update all destination paths
                config["fastdl"]["stories"]["destination_path"] = f"{base_path}/instagram/stories"
                config["fastdl"]["reels"]["destination_path"] = f"{base_path}/instagram/reels"
                config["imginn"]["tagged"]["destination_path"] = f"{base_path}/instagram/tagged"
                config["tiktok"]["destination_path"] = f"{base_path}/tiktok"

        # Immich
        if input("\nConfigure Immich integration? (y/n): ").lower() == 'y':
            config["immich"]["enabled"] = True
            api_url = input(f"Immich API URL [{config['immich']['api_url']}]: ").strip()
            if api_url:
                config["immich"]["api_url"] = api_url
            api_key = input("Immich API key: ").strip()
            if api_key:
                config["immich"]["api_key"] = api_key
            library_id = input("Immich Library ID (optional): ").strip()
            if library_id:
                config["immich"]["library_id"] = library_id

        # Pushover
        if input("\nConfigure Pushover notifications? (y/n): ").lower() == 'y':
            config["pushover"]["enabled"] = True
            user_key = input("Pushover user key: ").strip()
            if user_key:
                config["pushover"]["user_key"] = user_key
            api_token = input("Pushover API token: ").strip()
            if api_token:
                config["pushover"]["api_token"] = api_token

        # Save config
        with open(config_file, "w") as f:
            json.dump(config, f, indent=2)
        print(f"\nConfiguration saved to {config_file}")
    else:
        print(f"Configuration file already exists: {config_file}")

    # Create required directories
    print("\nCreating required directories...")
    dirs = ["logs", "temp", "database", "cookies", "sessions"]
    for d in dirs:
        Path(d).mkdir(exist_ok=True)
        print(f"  - {d}/")

    # Check for session files
    session_dir = Path("sessions")
    if session_dir.exists() and list(session_dir.glob("*")):
        print(f"\nFound Instagram sessions in {session_dir}")
    else:
        print("\nNo Instagram sessions found")
        print("For Instagram session-based downloads, place session files in sessions/")

    # Make scripts executable
    scripts = ["media-downloader.py", "db"]
    for script in scripts:
        if Path(script).exists():
            os.chmod(script, 0o755)

    if Path("scripts/install.sh").exists():
        os.chmod("scripts/install.sh", 0o755)
    if Path("scripts/uninstall.sh").exists():
        os.chmod("scripts/uninstall.sh", 0o755)

    print("\nSetup complete!")
    print("\nNext steps:")
    print("1. Edit config/settings.json to customize your configuration")
    print("2. For production install: sudo ./scripts/install.sh")
    print("3. For testing: python3 media-downloader.py --test")
    print()

if __name__ == "__main__":
    setup()
