#!/usr/bin/env python3
"""Make a new product folder: engine/ copied from this engine, data/ from a starter.

    bin/new-folder DIR                   data/ from the blank template
    bin/new-folder DIR --demo            data/ from the "Alex" demo life, dated today
    bin/new-folder DIR --data STARTER    data/ copied from any starter folder

DIR must not exist, or be empty. A folder that already holds engine/ or data/
is refused with one line: that is an update (bin/update-engine), never a new
folder, so nobody's data/ is ever overwritten here.

The demo arrives dated today: every YYYY-MM-DD in the copied data/ (file names
too) moves by the days between Alex's now.md `updated:` and today, so its need
lines are fresh and `check` passes. Then the no-model builds run (bin/summary,
bin/foryou build), one line each. Nothing outside DIR is touched.

The starters sit beside the engine: template/ and demo/alex/ in the product
repository, and the same two inside the app. Exit 0 and one line naming the
folder; exit 1 and one line on any refusal. Standard library only.
"""
import datetime
import os
import re
import shutil
import subprocess
import sys

sys.dont_write_bytecode = True  # no __pycache__ beside the engine's scripts
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import folder  # noqa: E402

ENGINE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
BESIDE = os.path.dirname(ENGINE)
DATE = re.compile(r"\b(20\d\d)-(\d\d)-(\d\d)\b")


def shift(text, days):
    def move(m):
        try:
            d = datetime.date(int(m[1]), int(m[2]), int(m[3]))
        except ValueError:
            return m[0]
        return (d + datetime.timedelta(days=days)).isoformat()
    return DATE.sub(move, text)


def date_today(data):
    """Move every date in data/ by the days from now.md's `updated:` to today. Returns (days, files)."""
    with open(os.path.join(data, "now.md"), encoding="utf-8") as fh:
        m = re.search(r"^updated: (\d{4}-\d{2}-\d{2})", fh.read(), re.M)
    if not m:
        return 0, 0
    days = (datetime.date.today() - datetime.date.fromisoformat(m[1])).days
    moved = 0
    for root, dirs, files in os.walk(data):
        dirs[:] = [d for d in dirs if d not in (".git", ".summary")]
        for name in files:
            path = os.path.join(root, name)
            try:
                with open(path, encoding="utf-8") as fh:
                    text = fh.read()
            except (UnicodeDecodeError, OSError):
                continue
            new = shift(text, days)
            if new != text:
                with open(path, "w", encoding="utf-8") as fh:
                    fh.write(new)
                moved += 1
            if DATE.search(name):
                os.rename(path, os.path.join(root, shift(name, days)))
    return days, moved


def build(top):
    """The no-model builds over the new folder. Returns how many failed."""
    env = dict(os.environ, LIFE_FOLDER=os.path.join(top, "data"), ENGINE_DIR=os.path.join(top, "engine"),
               PYTHONDONTWRITEBYTECODE="1")
    failed = 0
    for cmd in (["summary"], ["foryou", "build"]):
        p = subprocess.run([sys.executable, "-I", os.path.join(top, "engine", "bin", cmd[0])] + cmd[1:], cwd=top, env=env,
                           capture_output=True, text=True)
        last = ((p.stdout + p.stderr).strip().splitlines() or [""])[-1]
        print("%s: exit %d %s" % (" ".join(cmd), p.returncode, last))
        failed += p.returncode != 0
    return failed


def main(argv):
    args = list(argv)
    if not args or args[0] in ("-h", "--help"):
        print(__doc__.strip())
        return 0 if args else 1
    top = os.path.abspath(os.path.expanduser(args.pop(0)))
    starter = os.path.join(BESIDE, "template")
    if args[:1] == ["--demo"]:
        starter = os.path.join(BESIDE, "demo", "alex")
    elif args[:1] == ["--data"] and len(args) == 2:
        starter = os.path.abspath(os.path.expanduser(args[1]))
    elif args:
        print("usage: bin/new-folder DIR [--demo | --data STARTER]", file=sys.stderr)
        return 1
    if not os.path.isfile(os.path.join(starter, "now.md")):
        print("no starter at %s (it has no now.md)" % starter, file=sys.stderr)
        return 1
    if os.path.exists(top):
        if os.path.exists(os.path.join(top, "data")) or os.path.exists(os.path.join(top, "engine")):
            print("%s already holds a product folder; use bin/update-engine" % top, file=sys.stderr)
            return 1
        if [n for n in os.listdir(top) if n != ".DS_Store"]:
            print("%s is not empty; pick an empty or new folder" % top, file=sys.stderr)
            return 1
    os.makedirs(top, exist_ok=True)
    folder.copy_engine(ENGINE, os.path.join(top, "engine"))
    shutil.copytree(starter, os.path.join(top, "data"),
                    ignore=shutil.ignore_patterns(".summary", ".DS_Store", "__pycache__"))
    skills = folder.write_top(top, folder.embedder(ENGINE))
    print("%s: engine, data (from %s), %d skills" % (top, os.path.relpath(starter, BESIDE), len(skills)))
    if args[:1] == ["--demo"]:
        days, moved = date_today(os.path.join(top, "data"))
        print("demo: dates moved %+d days in %d files" % (days, moved))
        return 1 if build(top) else 0
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
