# interface/cli.py

import logging

import click

from rcdl.core import downloader as dl
from rcdl.core.config import Config
from rcdl.core.parser import get_creators, get_creator_from_line, parse_creator_input
from rcdl.core.db import DB
from rcdl.core.file_io import write_txt, load_txt
from .ui import UI


from rcdl import __version__


@click.command(help="Refresh video to be downloaded")
def refresh():
    """Update DB with all videos of creators"""
    UI.info("Welcome to RCDL refresh")

    creators = get_creators()
    dl.refresh_creators_videos(creators)

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

    UI.db_videos_status_table(info)


@click.command(help="Download all videos from all creator")
def dlsf():
    """Download video based on DB information"""

    UI.info("Welcome to RCDL dlsf")
    dl.download_videos_to_be_dl()


@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}"
    click.echo(msg)
    logging.info(msg)
    dl.discover(tag, max_page)


@click.command("add", help="Add a creator")
@click.argument("creator_input")
def add_creator(creator_input):
    """Add a creator (URL or str) to creators.txt"""
    if "coomer" in creator_input or "kemono" in creator_input or "://" in creator_input:
        parts = creator_input.replace("https://", "").strip().split("/")
        line = f"{parts[1]}/{parts[3]}"  # service, creator_id
        c = get_creator_from_line(line)
        if c:
            write_txt(Config.CREATORS_FILE, line)
        else:
            UI.warning("Could not extract creator from url input. Please check input")

    elif "/" in creator_input:
        c = get_creator_from_line(creator_input)
        if c:
            write_txt(Config.CREATORS_FILE, f"{c['service']}/{c['creator_id']}")
        else:
            UI.warning("Could not extract creator from str / input. Please check input")


@click.command("remove", help="Remove a creator")
@click.argument("creator_input")
def remove_creator(creator_input):
    """Remove a creator (excat line) from creators.txt"""
    service, creator_id = parse_creator_input(str(creator_input))

    lines = load_txt(Config.CREATORS_FILE)
    normalized = [line.strip() for line in lines]

    def matches(line: str) -> bool:
        if "/" not in line:
            return False
        line_service, line_creator = line.split("/", 1)
        # Full match
        if service and line_service == service and line_creator == creator_id:
            return True
        # Creator ID only match
        if service is None and line_creator == creator_id:
            return True
        return False

    new_lines = [line for line in normalized if not matches(line)]
    if len(new_lines) == len(normalized):
        UI.error(f"Could not find creator: {creator_input}")
        return

    write_txt(Config.CREATORS_FILE, new_lines, mode="w")
    UI.info(f"Removed creator: {creator_input}")


@click.command("list", help="List all creators")
def list_creators():
    creators = get_creators()
    UI.table_creators(creators)


# --- 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(discover)
cli.add_command(refresh)
cli.add_command(add_creator)
cli.add_command(remove_creator)
cli.add_command(list_creators)
