#!/usr/bin/env python3
# UserPromptSubmit hook. Reads the hook JSON on stdin, takes "prompt", and for
# each line starting with "No, actually" (any capitalization) appends one JSON
# line to corrections.jsonl beside this file: time (UTC), message (one random
# id per run), words (the whole line, exactly). Never changes or blocks the
# message. Always exits 0. If a correction cannot be saved, prints a JSON
# systemMessage starting "Correction NOT saved:".
import json
import os
import sys
import uuid
from datetime import datetime, timezone


def warn(reason):
    print(json.dumps({"systemMessage": "Correction NOT saved: " + reason}))


def main():
    try:
        data = json.loads(sys.stdin.read())
        prompt = data.get("prompt", "") if isinstance(data, dict) else ""
        if not isinstance(prompt, str):
            prompt = ""
    except Exception as e:
        warn("could not read the hook input as JSON (%s). Any No, actually line in this message was not recorded." % e)
        return
    lines = [l for l in prompt.splitlines() if l.lower().startswith("no, actually")]
    if not lines:
        return
    message = uuid.uuid4().hex
    now = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
    text = "".join(json.dumps({"time": now, "message": message, "words": l}) + "\n" for l in lines)
    path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "corrections.jsonl")
    try:
        with open(path, "a", encoding="utf-8") as f:
            f.write(text)
    except Exception as e:
        warn("could not write %s (%s). Lost: %s" % (path, e, " | ".join(lines)))


if __name__ == "__main__":
    try:
        main()
    except Exception as e:
        warn("unexpected error (%s)." % e)
    sys.exit(0)
