#!/usr/bin/env python3
"""PreToolUse (Read, Bash) hook: a memory read outside ownpast's recall is declined with the `ownpast memory` command
to run instead.

The shell parse is not airtight: an interpreter (`python -c`), `xargs`, a loop variable or a copy read later still
passes.
"""

from __future__ import annotations

import glob
import json
import os
import re
import shlex
import sys

import ownpast_hook

READERS = {"cat", "sed", "head", "tail", "less", "more", "bat", "awk", "nl"}
PREFIXES = {"!", "{", "do", "then", "else", "time", "exec", "command", "builtin", "nohup"}
NESTED = re.compile(r"\$\(|`|[()]")
ASSIGNMENT = re.compile(r"(\w+)=(.*)", re.S)
VARIABLE = re.compile(r"\$(?:\{(\w+)\}|(\w+))")


def heredoc_end(line):
    """The delimiter of a heredoc this line opens (`<<WORD`, `<<-WORD`, quoted or not), else None.
    A here-string (`<<<`) and `<<` inside quoted text open none."""
    try:
        words = shlex.split(line, posix=True)
    except ValueError:
        return None
    for i, word in enumerate(words):
        if word in ("<<", "<<-") and i + 1 < len(words):
            return words[i + 1]
        m = re.fullmatch(r"<<-?([^<\s].*)", word)
        if m and not word.startswith("<<<") and re.search(r"(?<!<)<<(?!<)", line):
            return m.group(1)
    return None


def lines(command):
    """The lines of a shell command, with heredoc bodies left out."""
    body_end = None
    for line in command.splitlines():
        if body_end is not None:
            if line.strip() == body_end:
                body_end = None
            continue
        body_end = heredoc_end(line)
        yield line


def segments(command):
    """Simple commands of a shell line, with heredoc bodies left out."""
    return [segment for line in lines(command) for segment in re.split(r"\|\||&&|[;|&]", line)]


def commands(line):
    """The word lists of a line's simple commands, split on `;`, `&` and `|` only where they stand unquoted."""
    lexer = shlex.shlex(line, posix=True, punctuation_chars=";&|")
    lexer.whitespace_split, lexer.commenters = True, ""
    try:
        tokens = list(lexer)
    except ValueError:
        tokens = re.sub(r"[;&|]+", " ; ", line).split()
    out = [[]]
    for token in tokens:
        if set(token) <= set(";&|"):
            out.append([])
        else:
            out[-1].append(token)
    return [words for words in out if words]


def nested(words):
    """The commands inside a command's `$(…)`, backticks and `( … )` groups, cut at those marks."""
    out = [[]]
    for word in words:
        pieces = NESTED.split(word)
        for i, piece in enumerate(pieces):
            if i:
                out.append([])
            if piece:
                out[-1].append(piece)
    return [words for words in out if words]


def runs_recall(words):
    """True when the words themselves run ownpast (directly or through python)."""
    while words and ASSIGNMENT.fullmatch(words[0]):
        words = words[1:]
    if words and re.fullmatch(r"python3?(\.\d+)?", os.path.basename(words[0])):
        words = [w for w in words[1:] if not w.startswith("-")]
    return bool(words) and os.path.basename(words[0]) in ("ownpast", "whaat")


def expand(word, env):
    """One word with its `$NAME`, `${NAME}` and leading `~` filled in; an unknown variable stays as written."""
    return os.path.expanduser(VARIABLE.sub(lambda m: env.get(m.group(1) or m.group(2), m.group(0)), word))


def read_targets(words):
    """The paths a reader command's words read, or [] when they are no read."""
    while words and (ASSIGNMENT.fullmatch(words[0]) or words[0] in PREFIXES):
        words = words[1:]
    if not words or os.path.basename(words[0]) not in READERS:
        return []
    if os.path.basename(words[0]) == "sed" and any(w == "-i" or w.startswith("-i") for w in words[1:]):
        return []
    targets, skip = [], False
    for word in words[1:]:
        if skip:
            skip = False
            continue
        if word in (">", ">>", "<<", "<<-", "2>", "&>"):
            skip = True
            continue
        if word.startswith((">", "<<")) or word.startswith("-"):
            continue
        targets.append(word)
    return targets


def block(rel):
    run = f'"{ownpast_hook.CLI}" memory'
    if os.path.basename(rel) == "MEMORY.md":
        how = (f'{run} index task="<what you are doing>" [path=<repo>]   (to list the triggers), or\n'
               f'  {run} open file={rel} because="<what you change>" purpose=save   (to edit the index)')
    else:
        how = (f'{run} open file={rel} because="<which words of its trigger match your task>"\n'
               f"  For a read that is not a recall add purpose=save, purpose=curate or purpose=review;\n"
               f'  for a whole dir: {run} dump dir={os.path.dirname(rel) or "."} purpose=curate because="<why>"')
    where = "your personal memories" if rel.startswith("personal:") else "the shared memory store"
    reason = (f"Not read: {rel} in {where} is opened only through memory-recall, so the log records "
              f"which trigger matched which task; a direct read leaves no trace. Instead run:\n  {how}\n"
              f"A Read of the file is allowed after that (for Edit). Continue the task after it.")
    print(json.dumps({"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "deny",
                                             "permissionDecisionReason": reason}}))


def check(event, paths, must_exist):
    """Ask ownpast about the .md paths among these (absolute, resolved); decline the first unopened memory."""
    paths = [p for p in paths if p.endswith(".md")]
    if not paths:
        return
    found = ownpast_hook.call("/api/v1/memory/recall/guard",
                            {"session": str(event.get("session_id", "")), "paths": paths, "must_exist": must_exist})
    if found and found.get("file"):
        block(found["file"])


def main():
    try:
        event = json.load(sys.stdin)
        tool, data = event["tool_name"], event.get("tool_input") or {}
    except (ValueError, KeyError, TypeError, AttributeError):
        return
    cwd = event.get("cwd") or os.getcwd()

    def absolute(path):
        return os.path.realpath(os.path.join(cwd, os.path.expanduser(path)))

    if tool == "Read":
        path = data.get("file_path", "")
        if path:
            check(event, [absolute(path)], must_exist=False)
        return
    if tool != "Bash":
        return
    try:
        targets = bash_reads(data.get("command", ""), cwd, dict(os.environ))
    except Exception:
        return
    check(event, targets, must_exist=True)


def bash_reads(command, cwd, env):
    """The absolute paths the reader commands of a shell line read, after its assignments and `cd`s so far.
    A command is read both whole and cut at its nested marks, since quoted text can hold those marks too."""
    targets = []
    for line in lines(command):
        for whole in commands(line):
            whole = [expand(word, env) for word in whole]
            parts = nested(whole)
            candidates = [whole] if parts == [whole] else [whole, *parts]
            for i, words in enumerate(candidates):
                if runs_recall(words):
                    continue
                while words and words[0] in PREFIXES:
                    words = words[1:]
                if words[:1] == ["export"]:
                    words = words[1:]
                steps = i > 0 or len(candidates) == 1
                if steps and words and all(ASSIGNMENT.fullmatch(word) for word in words):
                    env.update(ASSIGNMENT.fullmatch(word).groups() for word in words)
                    continue
                if steps and words[:1] in (["cd"], ["pushd"]):
                    places = [word for word in words[1:] if not word.startswith("-")]
                    cwd = os.path.realpath(os.path.join(cwd, places[0])) if places else os.path.expanduser("~")
                    continue
                for target in read_targets(words):
                    path = os.path.realpath(os.path.join(cwd, target))
                    targets += sorted(glob.glob(path)) if re.search(r"[*?[]", path) else [path]
    return targets


if __name__ == "__main__":
    main()
