#!/usr/bin/env ruby
# encoding: UTF-8
# frozen_string_literal: true

# validate-intent — deterministic CLI over IntentValidator (intent 60).
#
# Checks whether a single intent directory is born complete: required frontmatter
# fields present, and `sources`/`chain` well-formed arrays of id strings. The
# creating-intent skill self-verifies a freshly written intent with this CLI
# before announcing or committing; any agent or human can run it on one dir.
#
# Usage:
#   validate-intent <intent_dir> [--home <path>]
#
# Exit codes: 0 (born complete), 1 (incomplete; report on stderr), 2 (usage).
# --home <path> overrides the Plastic home (default: ~/.plastic).

require_relative "lib/intent_validator"
require_relative "lib/store_discovery"

def plastic_home(args)
  if (i = args.index("--home")) && args[i + 1]
    File.expand_path(args[i + 1])
  else
    File.expand_path(ENV["PLASTIC_HOME"] || "~/.plastic")
  end
end

home = plastic_home(ARGV)

# First positional arg, skipping any flag and the value that follows --home.
home_value_index = (i = ARGV.index("--home")) ? i + 1 : nil
intent_dir = ARGV.each_index.find do |idx|
  arg = ARGV[idx]
  !arg.start_with?("--") && idx != home_value_index
end
intent_dir = intent_dir && ARGV[intent_dir]

if intent_dir.nil?
  warn "usage: validate-intent <intent_dir> [--home <path>]"
  exit 2
end

dir = File.expand_path(intent_dir)
known_stores = StoreDiscovery.known_slugs(home)
result = IntentValidator.validate(dir, plastic_home: home, known_stores: known_stores)

if result[:ok]
  puts "OK: #{dir}"
  exit 0
end

warn "INCOMPLETE: #{dir}"
result[:missing].each { |field| warn "missing: #{field}" }
result[:errors].each { |error| warn error }
exit 1
