# frozen_string_literal: true

require 'minitest/autorun'
require 'tmpdir'
require 'fileutils'
require 'json'

# Add the plugin_config directory to the load path
$LOAD_PATH.unshift(File.expand_path('..', __dir__))

require 'file_locations'
require 'file_verifier'
require 'runtime_verifier'
require 'expectations'
require 'operations/enable'
require 'operations/disable'
require 'operations/register'
require 'operations/unregister'
require 'operations/audit'
require 'operations/list'
require 'operations/validate'

module TestHelpers
  def setup_temp_dirs
    @tmpdir = Dir.mktmpdir('plugin_config_test')
    @project_dir = File.join(@tmpdir, 'project')
    @settings_dir = File.join(@project_dir, '.claude')
    @marketplace_dir = @tmpdir
    FileUtils.mkdir_p(@settings_dir)
  end

  def teardown_temp_dirs
    FileUtils.rm_rf(@tmpdir) if @tmpdir && Dir.exist?(@tmpdir)
  end

  def settings_path
    File.join(@project_dir, '.claude', 'settings.json')
  end

  def marketplace_path
    File.join(@marketplace_dir, 'marketplace.json')
  end

  def create_settings(enabled_plugins = {})
    data = { 'enabledPlugins' => enabled_plugins }
    FileUtils.mkdir_p(File.dirname(settings_path))
    File.write(settings_path, JSON.pretty_generate(data) + "\n")
    settings_path
  end

  def create_marketplace(name: 'test-marketplace', plugins: [])
    data = { 'name' => name, 'plugins' => plugins }
    File.write(marketplace_path, JSON.pretty_generate(data) + "\n")
    marketplace_path
  end

  def create_installed_plugins(path, plugins = {})
    data = { 'plugins' => plugins }
    FileUtils.mkdir_p(File.dirname(path))
    File.write(path, JSON.pretty_generate(data) + "\n")
    path
  end

  def create_plugin_json(plugin_dir, name:, description:, extra: {})
    data = { 'name' => name, 'description' => description }.merge(extra)
    path = File.join(plugin_dir, '.claude-plugin', 'plugin.json')
    FileUtils.mkdir_p(File.dirname(path))
    File.write(path, JSON.pretty_generate(data) + "\n")
    path
  end

  def create_skill(plugin_dir, skill_name, with_skill_md: true)
    skill_dir = File.join(plugin_dir, 'skills', skill_name)
    FileUtils.mkdir_p(skill_dir)
    File.write(File.join(skill_dir, 'SKILL.md'), "# #{skill_name}\n") if with_skill_md
    skill_dir
  end

  def make_operation(klass, overrides = {})
    params = {
      plugin: 'test-plugin',
      marketplace: 'test-marketplace',
      project: @project_dir,
      marketplace_file: marketplace_path
    }.merge(overrides)
    klass.new(params)
  end
end
