from __future__ import annotations

import argparse
import logging
import sys
from typing import Iterable

from .api import scrape


def _configure_logging() -> logging.Logger:
    logging.basicConfig(level=logging.INFO, format="%(message)s", force=True, stream=sys.stdout)
    return logging.getLogger("scrape_forvo")


def _parse_args(argv: Iterable[str] | None) -> argparse.Namespace:
    ap = argparse.ArgumentParser()
    ap.add_argument("word", help="Word to search on Forvo, e.g. egg")
    ap.add_argument("-o", "--outdir", default="forvo_mp3", help="Output directory")
    ap.add_argument("--limit", type=int, default=1000, help="Max downloads")
    ap.add_argument("--dry-run", action="store_true", help="Print only; do not download")
    ap.add_argument("--no-head", action="store_true", help="Skip HEAD probe; try GET directly")
    ap.add_argument("--prefix", default=None, help="Filename prefix (default: derived from word)")
    ap.add_argument(
        "--use-playwright",
        action="store_true",
        help="Use Playwright to fetch HTML (bypasses many 403 blocks).",
    )
    ap.add_argument(
        "--headed",
        action="store_true",
        help="Show browser window (use if Cloudflare blocks headless; challenge often passes when visible).",
    )
    return ap.parse_args(argv)


def main(argv: Iterable[str] | None = None) -> int:
    args = _parse_args(argv)
    log = _configure_logging()
    result = scrape(
        args.word,
        outdir=args.outdir,
        limit=args.limit,
        dry_run=args.dry_run,
        no_head=args.no_head,
        prefix=args.prefix,
        use_playwright=args.use_playwright,
        headed=args.headed,
        emit=log.info,
    )

    if result.downloaded_count == 0:
        log.info("No MP3s downloaded (no valid Play(...) mp3 URLs found).")
        return 2

    return 0


if __name__ == "__main__":
    raise SystemExit(main())
