"""PreToolUse hook for Edit|Write|MultiEdit|Bash|Agent matchers.
Reads economy state file, emits additionalContext reminder of active level.
For Bash: detects file-modification patterns and emits warning.
For Agent: appends parent economy state to subagent prompt (closes H7)."""
import json
import os
import re
import sys
import tempfile

try:
    sys.stdin.reconfigure(encoding="utf-8", errors="replace")
except Exception:
    pass


BASH_FILE_MOD_PATTERNS = [
    r"\bsed\s+-i\b",
    r"\bsed\s+--in-place\b",
    r"\bOut-File\b",
    r"\bSet-Content\b",
    r"\becho\b[^|<>]*>\s*[^|>]",
    r"\btee\s",
    r"\bcat\s*>\s*",
    r"\bbash\s+-c\s+['\"][^'\"]*>",
    r"\bpython\s+-c\s+['\"][^'\"]*open\([^)]+,\s*['\"]w",
    r"\bgit\s+checkout\s+--",
    r"\bgit\s+reset\s+--hard",
]


LEVEL_TOPLINE = {
    100: None,
    75: "Жёсткие/мета OFF: НЕ заявлять passed без запуска, НЕ cherry-pick, НЕ anchor на 1й гипотезе",
    50: "Жёсткие/мета OFF + verify memory + ≥2 гипотезы на debug + full test output",
    25: "verify-before-completion на ≥2-step задачах, full reads ≤5000, Grep limit 500",
    5: "5% (0% без избыточности): full reads / тесты / ≥3 гипотезы / TDD как в 0%; без re-read CLAUDE.md, тест-каденс по логическим блокам, gitleaks-full-history -> pre-push, §12.2-floor для plan/brainstorm гейтов; скорость: параллельные tool-вызовы, без re-read неизменённого, дешёвая модель на механику, run_in_background, без лишних вопросов, фокус/компакт сессии",
    0: "ВСЕ паттерны OFF: full reads, full test output, ≥3 гипотезы на debug, verify perceived 'готово'",
}


def main() -> None:
    try:
        data = json.load(sys.stdin)
    except Exception:
        return

    sid = data.get("session_id")
    if not sid:
        return
    state_path = os.path.join(tempfile.gettempdir(), f"claude-economy-{sid}.json")
    if not os.path.exists(state_path):
        return
    try:
        with open(state_path, encoding="utf-8") as f:
            state = json.load(f)
    except Exception:
        return

    level = state.get("level")
    if level is None or level == 100:
        return

    label = state.get("label", f"{level}%")
    tail = state.get("tail", "")
    tool_name = data.get("tool_name", "")

    # Agent matcher: inject parent state into subagent prompt (closes H7)
    if tool_name == "Agent":
        tool_input = data.get("tool_input", {})
        original_prompt = tool_input.get("prompt", "")
        injected = (
            f"\n\n--- PARENT SESSION ECONOMY MODE ---\n"
            f"Inherited level: {label} — {tail}\n"
            f"Rules apply to your subagent work: {LEVEL_TOPLINE.get(level, '')}\n"
            f"---\n"
        )
        new_input = dict(tool_input)
        new_input["prompt"] = original_prompt + injected
        out = {
            "hookSpecificOutput": {
                "hookEventName": "PreToolUse",
                "additionalContext": f"Subagent inherits economy mode {label}",
                "updatedInput": new_input,
            }
        }
        sys.stdout.write(json.dumps(out, ensure_ascii=True))
        return

    # Edit/Write/MultiEdit/Bash: emit reminder
    notes = []
    topline = LEVEL_TOPLINE.get(level)
    if topline:
        notes.append(f"REMINDER: активна экономия {label}. {topline}")

    if tool_name == "Bash":
        cmd = data.get("tool_input", {}).get("command", "")
        for pat in BASH_FILE_MOD_PATTERNS:
            if re.search(pat, cmd, re.IGNORECASE):
                notes.append(
                    "WARNING: Bash содержит file-modification pattern. "
                    "Mode требует тестов после правок code-файлов — "
                    "Bash-обход Edit/Write не освобождает от обязательств."
                )
                break

    if notes:
        out = {
            "hookSpecificOutput": {
                "hookEventName": "PreToolUse",
                "additionalContext": "\n\n".join(notes),
            }
        }
        sys.stdout.write(json.dumps(out, ensure_ascii=True))


if __name__ == "__main__":
    main()
