#!/usr/bin/env python3
"""fzf-based selectors for comic and gallery links."""
from __future__ import annotations

import re
import subprocess

import db

USER = "jawz"

RGX_COMIC = re.compile("readcomiconline|mangahere|mangadex|webtoons|manganato")


def _select_links(urls: list[str]) -> list[str]:
    if not urls:
        return []
    proc = subprocess.run(
        ["fzf", "--multi", "--exact", "-i"],
        input="\n".join(urls),
        text=True,
        capture_output=True,
        check=False,
    )
    if proc.returncode != 0:
        return []
    return [ln for ln in proc.stdout.splitlines() if ln.strip()]


def _run_download(selected: list[str]) -> None:
    if not selected:
        return
    subprocess.run(["download", "-u", USER, "-i", *selected], check=False)


def comic_main() -> None:
    with db.connect() as conn:
        rows = db.get_links(conn, users=[USER], include_disabled=False, include_banned=False)
    urls = [row["url_original"] for row in rows if RGX_COMIC.search(row["url_original"])]
    _run_download(_select_links(urls))


def gallery_main() -> None:
    with db.connect() as conn:
        rows = db.get_links(conn, users=[USER], include_disabled=False, include_banned=False)
    urls = [row["url_original"] for row in rows if not RGX_COMIC.search(row["url_original"])]
    _run_download(_select_links(urls))


if __name__ == "__main__":
    gallery_main()
