#!/usr/bin/env python3
"""
Dependency-free manga archiver. Download all chapters of a manga from a
supported source into <archive_dir>/chapter_XXX/page_001.ext, ...

Usage:
  python3 download.py drake [manga_url]
      Drake Scans (drakecomic.org). Defaults to the original target:
      https://drakecomic.org/manga/disastrous-necromancer/

  python3 download.py mangaread manga_url
      MangaRead (mangaread.org), e.g.:
      python3 download.py mangaread \
          https://www.mangaread.org/manga/return-of-the-runebound-professor/

Behaviour (all sources):
  - Polite: single sequential connection, fixed delays between requests,
    longer breather every 25 images, exponential backoff, and a full stop
    if 429s persist.
  - Resumable / self-healing: re-running reconciles every chapter
    directory with the site's canonical page list (renames existing files
    to page_NNN names, downloads missing pages, removes stray files).
    Details in <archive_dir>/download_state.json.

After a download completes, run generate_html.py on the archive dir to
build the static reader pages.
"""

import sys

from manga import DrakeScansSource, MangaReadSource
from manga.core import run

DEFAULTS = {
    "drake": "https://drakecomic.org/manga/disastrous-necromancer/",
}


def make_source(name: str, url: str | None):
    if name == "drake":
        slug = None
        if url:
            import re
            m = re.search(r"/manga/([^/]+)/?$", url)
            if m:
                slug = m.group(1)
        return DrakeScansSource(slug)
    if name == "mangaread":
        if not url:
            sys.exit("mangaread requires a manga URL.\n" + __doc__)
        return MangaReadSource()
    sys.exit(f"Unknown source '{name}'. Supported: {', '.join(SOURCES)}")


SOURCES = ["drake", "mangaread"]


def main() -> None:
    args = sys.argv[1:]
    if not args:  # legacy: bare `python3 download.py` == drake default
        name, url = "drake", None
    else:
        name = args[0]
        url = args[1] if len(args) > 1 else None
        if not url and DEFAULTS.get(name):
            url = DEFAULTS[name]
    if not url:
        sys.exit(f"{name} requires a manga URL.\n" + __doc__)
    run(make_source(name, url), url)


if __name__ == "__main__":
    main()
