import typer
from pathlib import Path
from typing import Optional

from .services.channel_manager import ChannelManager
from .services.cookies_extractor import CookiesExtractor
from .services.video_downloader import VideoDownloader


app = typer.Typer(help="Youthsee – YouTube knowledge pipeline")


# ─────────────────────────
# 🍪 Cookies
# ─────────────────────────

@app.command("show-cookies")
def show_cookies():
    """
    Show extracted YouTube cookies from browser (debug purpose).
    """
    print(CookiesExtractor().export_cookies_str(domain="youtube.com"))


@app.command("save-cookies")
def save_cookies(
    output: Path = typer.Option("cookies.txt", help="Output cookies.txt"),
):
    """
    Export YouTube cookies to cookies.txt (Netscape format).
    """
    CookiesExtractor().export_cookies_txt(output_file=output, domain="youtube.com")
    typer.echo(f"✅ Cookies saved to {output}")


# ─────────────────────────
# 🎬 Download
# ─────────────────────────

@app.command("download-video")
def download_video(
    url: str = typer.Argument(..., help="YouTube video URL"),
    cookies: Path = typer.Option("cookies.txt", help="cookies.txt"),
    outdir: Path = typer.Option("~/Downloads/_YouthSee", help="Output directory"),
):
    """
    Download YouTube video.
    """
    CookiesExtractor().export_cookies_txt(cookies, domain="youtube.com")
    VideoDownloader(outdir).download(url)
    typer.echo(f"⬇️ Video has downloaded to: {outdir}")


# ─────────────────────────
# 📋 List videos
# ─────────────────────────

@app.command("list-videos")
def list_videos(
    channel_url: str = typer.Argument(..., help="Channel URL"),
    only: Optional[str] = typer.Option(
        None, help="Filter: video | short | live"
    ),
):
    """
    List videos in a channel (optionally filter shorts/live).
    """
    cm = ChannelManager(channel_url=channel_url)
    videos = cm.get_video_infos()

    for v in videos:
        typer.echo(
            f"{v['title']:<90} ({v['duration']}s)"
        )

    typer.echo(f"\nTotal: {len(videos)}")
