#!/usr/bin/env python3
"""0432, his test 2026-10-31 14:48: the greeting said "Four things need you; the oldest: enterprise
brain: say whether the old agents used MCP tools (enterprise-brain). Two decisions wait on your
word." The chat's "what needs me" read now.md alone, found three reminders and no decision, and
Argoni denied what it had said. The reader must give the letter's own items: the same needs, the
same oldest, the same decisions.

    engine/tests/letter-needs-test [READER]   (default: this engine's bin/argoni-read)
"""
import json
import datetime
import hashlib
import os
import pathlib
import subprocess
import sys
import tempfile

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

NOW = """# Now

## What needs you
- Stretch (reminder, 30 October)
- stan (reminder, 30 October)
- stan (reminder, today)
"""

# His for-you.json as the greeting read it: a project report waiting since 17 October (the oldest),
# the three reminder lines from now.md, two decisions proposed in a project.
LETTER = {
    "version": 1, "generated_at": "2026-10-31T14:48:00+03:00",
    "needs": [
        {"key": "need:a1", "source": "now.md", "since": "2026-10-30", "project": None,
         "for_you": {"headline": "Stretch", "body": None}},
        {"key": "need:report-eb", "source": "project-report", "since": "2026-10-17", "project": "enterprise-brain",
         "for_you": {"headline": "Enterprise brain: say whether the old agents used MCP tools.", "body": "Question 1 of six."}},
        {"key": "need:a2", "source": "now.md", "since": "2026-10-30", "project": None,
         "for_you": {"headline": "stan", "body": None}},
        {"key": "need:a3", "source": "now.md", "since": "2026-10-31", "project": None,
         "for_you": {"headline": "stan", "body": None}},
    ],
    "decisions": [
        {"key": "dec:1", "project": "enterprise-brain", "repo": "enterprise-brain", "path": "docs/decisions/0007-keep.md",
         "id": "0007", "status": "proposed", "date": "2026-10-29", "name": "Keep old decisions in the Decisions file",
         "for_you": {"decided": "Keep old decisions in one file."}},
        {"key": "dec:2", "project": "enterprise-brain", "repo": "enterprise-brain", "path": "docs/decisions/0008-c1.md",
         "id": "0008", "status": "waiting on the owner", "date": "2026-10-20", "name": "Continue C1 or write it up"},
        {"key": "dec:3", "project": None, "path": "decisions/0001-old.md", "id": "0001", "status": "accepted",
         "days_to_revisit": 40, "name": "An old one, not waiting"},
    ],
}


def main(argv):
    reader = argv[0] if argv else str(ENGINE / "bin" / "argoni-read")
    with tempfile.TemporaryDirectory() as tmp:
        data = pathlib.Path(tmp) / "Folder" / "data"
        (data / ".summary").mkdir(parents=True)
        (data / "now.md").write_text(NOW)
        (data / ".summary" / "for-you.json").write_text(json.dumps(LETTER))
        p = subprocess.run([sys.executable, "-I", reader, "needs", str(data.parent)], capture_output=True, text=True, timeout=30,
                           env=dict(os.environ, PYTHONDONTWRITEBYTECODE="1"))
        assert p.returncode == 0, p.stderr
        items = json.loads(p.stdout)["items"]
        needs = [i for i in items if i.get("kind") == "need"]
        decisions = [i for i in items if i.get("kind") == "decision"]
        fails = []
        if len(needs) != 4:
            fails.append("the letter counts four needs; the reader gave %d: %s" % (len(needs), [i["text"] for i in needs]))
        if not needs or not needs[0]["text"].startswith("Enterprise brain"):
            fails.append("the oldest is not the enterprise brain: %s" % (needs[0]["text"] if needs else None))
        if len(decisions) != 2:
            fails.append("two decisions wait on his word; the reader gave %d" % len(decisions))
        elif not decisions[0]["text"].startswith("Continue C1"):
            fails.append("the decisions are not oldest first: %s" % [d["text"] for d in decisions])
        if fails:
            print("letter-needs-test: FAIL\n  " + "\n  ".join(fails))
            return 1
        # 0437: his three fired one-offs from prior days must leave Needs you even when
        # the letter cache still holds their old words. Today's Later window stays.
        yesterday = (datetime.date.today() - datetime.timedelta(days=1)).isoformat()
        today = datetime.date.today().isoformat()
        lines = ["remind-a: reminder, Stretch (scheduled remind-a). (from log/%s.md; checked %s)" % (yesterday, today),
                 "remind-b: reminder, stan (scheduled remind-b). (from log/%s.md; checked %s)" % (yesterday, today),
                 "remind-c: reminder, stan (scheduled remind-c). (from log/%s.md; checked %s)" % (yesterday, today),
                 "remind-d: reminder, drink (scheduled remind-d). (from log/%s.md; checked %s)" % (today, today)]
        (data / "now.md").write_text("# Now\n\n## What needs you\n" + "\n".join("- " + x for x in lines) + "\n")
        letter = {"version": 1, "needs": [{"key": "need:" + hashlib.sha1((x + "\0").encode()).hexdigest()[:10],
                                            "source": "now.md", "for_you": {"headline": x.split(": ", 1)[1]}}
                                           for x in lines]}
        (data / ".summary" / "for-you.json").write_text(json.dumps(letter))
        p = subprocess.run([sys.executable, "-I", reader, "needs", str(data.parent)], capture_output=True, text=True,
                           env=dict(os.environ, PYTHONDONTWRITEBYTECODE="1"))
        remaining = json.loads(p.stdout)["items"] if p.returncode == 0 else []
        assert len(remaining) == 1 and "drink" in remaining[0]["text"], remaining
        (data / ".summary" / "for-you.json").unlink()
        p = subprocess.run([sys.executable, "-I", reader, "needs", str(data.parent)], capture_output=True, text=True,
                           env=dict(os.environ, PYTHONDONTWRITEBYTECODE="1"))
        remaining = json.loads(p.stdout)["items"] if p.returncode == 0 else []
        assert len([x for x in remaining if x.get("kind") == "need"]) == 1, remaining
    print("letter-needs-test: PASS")
    return 0


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