# medsos_downloader/__main__.py

import click
import sys
from rich.console import Console
from rich.prompt import Prompt
from .downloader import download_media
from .__version__ import __version__

console = Console()

PLATFORMS = {
    "1": "tiktok",
    "2": "instagram",
    "3": "facebook",
    "4": "youtube-mp4",
    "5": "youtube-mp3",
}

def show_menu():
    console.print("\n[bold cyan]🎥 Medsos Downloader[/bold cyan]")
    console.print("\n[bold cyan]*ketik medsosdl --help untuk bantuan[/bold cyan]\n")
    console.print("Pilih platform:")
    console.print("1. TikTok")
    console.print("2. Instagram")
    console.print("3. Facebook")
    console.print("4. YouTube (MP4)")
    console.print("5. YouTube (MP3)")
    console.print("0. Keluar\n")

def detect_platform_from_url(url: str):
    url = url.lower()
    if "tiktok.com" in url:
        return "tiktok"
    elif "instagram.com" in url:
        return "instagram"
    elif "facebook.com" in url or "fb.watch" in url:
        return "facebook"
    elif "youtube.com" in url or "youtu.be" in url:
        return "youtube-mp4"
    return None

@click.command()
@click.argument('url', required=False, default="")
@click.option('--version', is_flag=True, help='Tampilkan versi aplikasi')
def main(url: str, version: bool):
    """
    🎥 **Medsos Downloader** – Unduh video & audio dari media sosial via terminal!
    
    ✨ Fitur:
      • TikTok (tanpa watermark)
      • Instagram (video & foto)
      • Facebook (HD/SD)
      • YouTube (MP4 & MP3)
    
    📥 File otomatis disimpan di: ~/Downloads/medsos-downloader/
    
    📌 Contoh Penggunaan:
      $ medsosdl                                    # Tampilkan menu interaktif
      $ medsosdl https://www.tiktok.com/@user/video/123
      $ medsosdl https://www.instagram.com/reel/ABC123/
      $ medsosdl https://www.facebook.com/watch?v=12345
      $ medsosdl https://youtu.be/xyz789
    
    ⚠️ Catatan:
      • Pastikan URL publik (tidak dari akun privat).
      • Gunakan secara bertanggung jawab sesuai ToS platform.
    """
    if version:
        console.print(f"[cyan]medsos-downloader[/cyan] v{__version__}")
        sys.exit()
    
    if not url:
        # Mode interaktif
        while True:
            show_menu()
            choice = Prompt.ask("Masukkan pilihan", default="0")
            
            if choice == "0":
                console.print("[yellow]Sampai jumpa![/yellow]")
                sys.exit()
            
            if choice not in PLATFORMS:
                console.print("[red]Pilihan tidak valid. Coba lagi.[/red]")
                continue

            platform = PLATFORMS[choice]
            url_input = Prompt.ask(f"\n🔗 Masukkan URL {platform.replace('-', ' ').title()}")
            
            try:
                download_media(url_input, platform=platform)
                break
            except Exception as e:
                console.print(f"[red]❌ Error: {e}[/red]")
                console.print("[dim]Tekan Enter untuk coba lagi...[/dim]")
                input()
    else:
        # Mode langsung: deteksi platform dari URL
        platform = detect_platform_from_url(url)
        if not platform:
            console.print("[red]URL tidak dikenali. Didukung: TikTok, Instagram, Facebook, YouTube.[/red]")
            sys.exit(1)
        download_media(url, platform=platform)

if __name__ == "__main__":
    main()