#!/usr/bin/env python3
# fanfictioner: turn a story idea into a text-free illustrated book.
# Copyright (C) 2026 Danilo M. <danix@danix.xyz>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

import argparse
import json
import os
import random
import re
import shlex
import shutil
import subprocess
import sys
import tempfile
import time
import urllib.request
from pathlib import Path

LLM_URL = "http://localhost:8181"
LLM_MODEL = "Gemma4-12B-qat-mtp"
SD_DIR = Path("/data/LLM-models/SD")
CONF = Path.home() / ".config/book-reader.conf"


def load_conf(path=CONF):
    conf = {}
    for line in path.read_text().splitlines():
        if "=" in line and not line.lstrip().startswith("#"):
            k, v = line.split("=", 1)
            conf[k.strip()] = shlex.split(v)[0] if v.strip() else ""
    return conf


def page_path(lib, pj, n):
    return Path(lib) / pj["series"] / pj["book"] / f"{n:03d}.png"


def todo(pj, wd, lib):
    """What is left to do, derived from disk: (characters without a ref, pages not in the library)."""
    refs = [c for c in pj["characters"] if not (wd / "refs" / f"{c['name']}.png").exists()]
    pages = [p for p in pj["pages"] if not page_path(lib, pj, p["n"]).exists()]
    return refs, pages


def keep(src, dst):
    """Copy src to dst atomically, so a half-written file never counts as done."""
    dst.parent.mkdir(parents=True, exist_ok=True)
    tmp = dst.with_name(dst.name + ".tmp")
    shutil.copyfile(src, tmp)
    os.replace(tmp, dst)
    return dst


def selftest():
    with tempfile.TemporaryDirectory() as t:
        t = Path(t)
        (t / "c.conf").write_text('# comment\nLIBRARY="/data/my lib"\nPORT=8642\n')
        conf = load_conf(t / "c.conf")
        assert conf == {"LIBRARY": "/data/my lib", "PORT": "8642"}, conf

        pj = {"series": "S", "book": "B",
              "characters": [{"name": "Mara"}, {"name": "Jon"}],
              "pages": [{"n": 1}, {"n": 2}]}
        lib = t / "lib"
        assert page_path(lib, pj, 7) == lib / "S" / "B" / "007.png"
        (t / "refs").mkdir()
        (t / "refs" / "Mara.png").touch()
        page_path(lib, pj, 1).parent.mkdir(parents=True)
        page_path(lib, pj, 1).touch()
        refs, pages = todo(pj, t, lib)
        assert [c["name"] for c in refs] == ["Jon"], refs
        assert [p["n"] for p in pages] == [2], pages

        keep(t / "refs" / "Mara.png", t / "deep" / "x.png")
        assert (t / "deep" / "x.png").exists()
    print("selftest ok")


def main():
    ap = argparse.ArgumentParser(description="Turn story.md into a text-free illustrated book.")
    ap.add_argument("story", nargs="?", type=Path, help="story idea in free prose")
    ap.add_argument("--base", choices=("zimage", "krea2"), default="zimage",
                    help="base model for pages without a Model: line")
    ap.add_argument("--selftest", action="store_true", help="run built-in checks and exit")
    a = ap.parse_args()
    if a.selftest:
        return selftest()
    if not a.story:
        ap.error("story file required")


if __name__ == "__main__":
    main()
