# interface/cli.py

import logging
import os.path

import click

from rcdl.utils import echo, echoc
from rcdl.core import downloader as dl
from rcdl.core.config import Config
from rcdl.core.processor import fuse_all_videos
from rcdl.core.parser import get_creators
from rcdl.core.db import DB


from rcdl import __version__


@click.command(help="Refresh video to be downloaded")
def refresh():
    """
    Find all videos of creators
    """
    creators = get_creators()
    logging.info("[cdl] refresh")
    dl.refresh_creators_videos(creators)

    with DB() as db:
        info = db.get_db_videos_info()

    for key in ["not_downloaded", "downloaded", "failed", "skipped", "ignored"]:
        logging.info(f"{key}: {info[key]}")


@click.command(help="Download all videos from all creator")
def dlsf():
    """
    Download settings file
    Name was kept from pototype despite functionnality changing.
    """

    logging.info("[cdl] dlsf")
    dl.download_videos_to_be_dl()


@click.command(help="Show log info")
def log():
    """Show the log file in the terminal"""
    if not os.path.exists(Config.LOG_FILE):
        echoc(f"Logging file {Config.LOG_FILE} does not exist", "red")
        return

    try:
        with open(Config.LOG_FILE, "r") as f:
            logs = f.read()

        os.environ["LESS"] = os.environ.get("LESS", "") + " +G"
        click.echo_via_pager(logs)

    except Exception as e:
        echoc(f"Failed to display log content due to error: {e}", "red")


@click.command(help="Fuse multiple part video into one")
def fuse():
    """Fuse all videos of creators that are in multiple parts"""
    echoc("[cdl] fuse", "white")
    logging.info("[cdl] fuse")

    creators = get_creators()
    if Config.DEBUG and len(creators) > 1:
        creators = creators[0:1]

    fuse_all_videos(creators)


@click.command(help="Discover videos/creators with tags")
@click.option("--tag", required=True, type=str, help="Tag to search for")
@click.option(
    "--max-page", default=10, type=int, help="Maximum number of pages to fetch"
)
def discover(tag, max_page):
    """Discover new creators/videos"""
    msg = f"[cdl] discover with tag={tag} max_page={max_page}"
    echo(msg)
    logging.info(msg)
    dl.discover(tag, max_page)


# --- CLI GROUP ---
@click.group()
@click.option("--debug", is_flag=True)
@click.option("--dry-run", is_flag=True)
@click.version_option(version=__version__, prog_name=Config.APP_NAME)
def cli(debug, dry_run):
    Config.set_debug(debug)
    Config.set_dry_run(dry_run)


cli.add_command(dlsf)
cli.add_command(log)
cli.add_command(fuse)
cli.add_command(discover)
cli.add_command(refresh)
