#!/usr/bin/env ruby
# encoding: UTF-8
# Usage: hook-future-intent-check <store_root> <message>
# Outputs hook JSON when the user's message matches future intent keywords.
# Exits silently if no matches.

require "json"
require "yaml"

store_root, message = ARGV
exit 0 unless store_root && message

index_path = "#{store_root}/INDEX.md"
exit 0 unless File.exist?(index_path)

# --- Find future intent dirs ---

lines = File.readlines(index_path)
future_dirs = []
section = nil

lines.each do |line|
  section = :future if line.start_with?("## Future")
  section = nil if line.start_with?("## ") && !line.start_with?("## Future")
  next unless section == :future && line.strip.start_with?("- [")

  if line =~ /store\/([\w-]+)\//
    future_dirs << $1
  end
end

exit 0 if future_dirs.empty?

# --- Match keywords against message ---

matches = []
message_words = message.split(/\W+/).reject { |w| w.length < 4 }

future_dirs.each do |dir|
  intent_path = "#{store_root}/store/#{dir}/#{dir}.md"
  next unless File.exist?(intent_path)

  content = File.read(intent_path)

  tags = []
  if content =~ /^tags:\s*\[([^\]]+)\]/
    tags = $1.split(",").map(&:strip).map(&:downcase)
  end

  intent_name = ""
  if content =~ /^intent:\s*["']?(.+?)["']?\s*$/
    intent_name = $1.downcase
  end

  intent_id = ""
  if content =~ /^id:\s*["']?([a-z0-9]+)["']?\s*$/
    intent_id = $1
  end

  keywords = tags + intent_name.split(/\W+/).reject { |w| w.length < 4 }
  keywords = keywords.map(&:downcase).uniq

  matched_keywords = keywords.select { |kw| message.include?(kw) }
  name_matches = message_words.select { |w| intent_name.include?(w) }
  matched_keywords = (matched_keywords + name_matches).uniq

  if matched_keywords.length >= 1
    index_line = lines.find { |l| l.include?(dir) }&.strip || "#{intent_id} — #{intent_name}"
    matches << { "index_line" => index_line, "keywords" => matched_keywords }
  end
end

exit 0 if matches.empty?

# --- Build context ---

parts = []
parts << "PLASTIC — Future intents related to this message:\n"
matches.each do |m|
  parts << "#{m["index_line"]} (matched: #{m["keywords"].join(", ")})"
end
parts << "\nConsider asking the user if they want to activate any of these, or note the connection."

payload = {
  "hookSpecificOutput" => {
    "hookEventName" => "UserPromptSubmit",
    "additionalContext" => parts.join("\n")
  }
}
puts JSON.generate(payload)
