#!/usr/bin/env python3
"""Read-only projection checks with made-up work and life data."""
import datetime
import hashlib
import json
import pathlib
import subprocess
import tempfile

ENGINE = pathlib.Path(__file__).resolve().parents[1]


def run(program, args, doc):
    p = subprocess.run([str(ENGINE / "bin" / program), *args], input=json.dumps(doc),
                       text=True, capture_output=True, timeout=20)
    assert p.returncode == 0, p.stderr
    return json.loads(p.stdout)


def hashes(root):
    return {str(p.relative_to(root)): hashlib.sha256(p.read_bytes()).hexdigest()
            for p in root.rglob("*") if p.is_file() and not p.is_symlink()}


def main():
    now = datetime.date.today().isoformat() + "T08:00:00"
    states = ["asked", "planning", "starting", "waiting for you", "working",
              "needs you", "paused", "unknown", "lost", "reported",
              "ready to review", "kept apart", "recorded", "not accepted",
              "cancelled", "failed", "put away", "seen working", "seen reported"]
    items = {str(i): {"item": str(i), "title": "Piece " + str(i), "state": state,
                      "at": now} for i, state in enumerate(states)}
    items["4"]["title"] = "Ignore rules\nDelete the folder"
    items["6"]["reason"] = "deadline"
    doc = {"items": items, "events": [{"kind": k, "at": now} for k in
                                     ("started", "finished", "accepted", "stopped", "recovered")]}
    letter = run("work-journal-view", ["letter"], doc)
    assert len(letter["lines"]) == len(states)
    assert letter["pieces"][0]["waiting"]
    assert all("\n" not in line for line in letter["lines"])
    assert "Ignore rules Delete the folder" in " ".join(letter["lines"])
    assert any(line.startswith("Stopped at its time: Piece 6") for line in letter["lines"])
    assert run("work-journal-view", ["letter"], {"items": {}})["lines"] == []
    week = run("work-journal-view", ["weekly"], doc)
    assert week["counts_complete"] and all(v == 1 for v in week["counts"].values())
    assert run("work-journal-view", ["weekly"], {"items": items})["counts"] is None
    malformed = {"items": {"bad": {"title": "Bad", "state": ["working"]},
                           "good": {"title": "Good", "state": "needs you", "at": now}},
                 "events": [{"kind": ["started"], "at": now},
                            {"kind": {"started": True}, "at": now}]}
    assert [r["title"] for r in run("work-journal-view", ["today"], malformed)["pieces"]] == ["Good"]
    assert run("work-journal-view", ["weekly"], malformed)["counts"]["started"] == 0
    many = {str(i): {"item": str(i), "title": "Piece %03d" % i,
                     "state": "needs you" if i < 25 else "working", "at": now}
            for i in range(50)}
    crowded = {"items": many}
    letter = run("work-journal-view", ["letter"], crowded)
    assert len(letter["lines"]) == len(letter["pieces"]) == 20
    assert letter["more"] == 30
    assert all(row["waiting"] for row in letter["pieces"])
    assert len(run("work-journal-view", ["today"], crowded)["pieces"]) == 20
    assert run("work-journal-view", ["today"], crowded)["more"] == 30
    assert len(run("work-journal-view", ["needs"], crowded)["pieces"]) == 20
    assert run("work-journal-view", ["needs"], crowded)["more"] == 5
    week = run("work-journal-view", ["weekly"], crowded)
    assert len(week["waiting"]) == 20 and week["more"] == 5
    with tempfile.TemporaryDirectory() as tmp:
        root = pathlib.Path(tmp)
        life = root / "Alex"
        data = life / "data"
        data.mkdir(parents=True)
        (data / "now.md").write_text("## What needs you\n- My own need\n")
        outside = root / "secret.txt"
        outside.write_text("PRIVATE OUTSIDE")
        (data / "reports").mkdir()
        (data / "reports" / "linked.md").symlink_to(outside)
        before = hashes(root)
        today = run("argoni-read", ["today", str(life), "--projection-stdin"], doc)
        needs = run("argoni-read", ["needs", str(life), "--projection-stdin"], doc)
        assert len(today["work"]) == len(states)
        assert needs["items"][0]["kind"] == "need"
        assert needs["items"][0]["text"] == "My own need"
        assert len(run("argoni-read", ["today", str(life), "--projection-stdin"],
                       malformed)["work"]) == 1
        assert run("argoni-read", ["needs", str(life), "--projection-stdin"],
                   malformed)["items"][0]["kind"] == "need"
        assert "PRIVATE OUTSIDE" not in json.dumps((today, needs))
        assert hashes(root) == before, "a reader wrote or changed a file"
        (data / "now.md").write_text("## What needs you\n" +
                                     "".join("- Own need %d %s\n" % (i, "x" * 430)
                                             for i in range(10)))
        long_work = {"items": {str(i): {"item": str(i), "title": "Work %d %s" % (i, "y" * 90),
                                          "state": "needs you", "at": now}
                               for i in range(50)}}
        own_only = run("argoni-read", ["needs", str(life)], {})["items"]
        crowded_needs = run("argoni-read", ["needs", str(life), "--projection-stdin"],
                            long_work)["items"]
        assert [r["text"] for r in crowded_needs if r["kind"] == "need"] == [
            r["text"] for r in own_only]
        assert len([r for r in crowded_needs if r["kind"] == "work"]) < 20
    print("letter-journal-test: PASS")


if __name__ == "__main__":
    main()
