require 'rspec'
require 'jekyll'
require 'tempfile'
require 'fileutils'
require 'mini_magick'
require_relative '../lib/jekyll-skyhook'

RSpec.configure do |config|
  config.expect_with :rspec do |expectations|
    expectations.include_chain_clauses_in_custom_matcher_descriptions = true
  end

  config.mock_with :rspec do |mocks|
    mocks.verify_partial_doubles = true
  end

  config.shared_context_metadata_behavior = :apply_to_host_groups
end

def create_test_site(show_drafts: false)
  source = Dir.mktmpdir('jekyll-skyhook-test')
  dest = Dir.mktmpdir('jekyll-skyhook-dest')
  cache = Dir.mktmpdir('jekyll-skyhook-cache')

  config = Jekyll.configuration({
    'source' => source,
    'destination' => dest,
    'cache_dir' => cache,
    'show_drafts' => show_drafts,
    'skyhook' => {
      'asset_dirs' => ['assets'],
      'digest_dir' => '_digested'
    }
  })

  site = Jekyll::Site.new(config)

  # Create assets directory
  FileUtils.mkdir_p(File.join(source, 'assets'))

  site
end

def create_test_image(site, path, width = 100, height = 100)
  full_path = File.join(site.source, path)
  FileUtils.mkdir_p(File.dirname(full_path))

  ext = File.extname(path).downcase

  case ext
  when '.svg'
    # Create a simple SVG file
    svg_content = <<~SVG
      <svg width="#{width}" height="#{height}" xmlns="http://www.w3.org/2000/svg">
        <rect width="#{width}" height="#{height}" fill="blue"/>
      </svg>
    SVG
    File.write(full_path, svg_content)
  when '.woff', '.woff2', '.ttf', '.eot'
    # Create a dummy font file (just some binary content)
    File.write(full_path, "\x00\x01\x00\x00\x00\x0f\x00\x80\x00\x03\x00\x70GDEF", encoding: 'ASCII-8BIT')
  else
    # Use ImageMagick command directly to create a test image
    format = case ext
    when '.jpg', '.jpeg' then 'jpeg'
    when '.png' then 'png'
    when '.webp' then 'webp'
    when '.avif' then 'avif'
    else 'jpeg'
    end

    # Create image using convert command
    system("convert -size #{width}x#{height} xc:blue #{full_path}")

    unless File.exist?(full_path)
      # Fallback: create a minimal valid image file
      File.write(full_path, "\xFF\xD8\xFF\xE0\x00\x10JFIF") if ext == '.jpg'
    end
  end

  full_path
end

def create_test_css(site, path, content = nil)
  full_path = File.join(site.source, path)
  FileUtils.mkdir_p(File.dirname(full_path))

  default_content = <<~CSS
    /* Test CSS file */
    body {
      font-family: Arial, sans-serif;
      background-color: #f0f0f0;
      margin: 0;
      padding: 20px;
    }

    .header {
      background: url('images/header-bg.jpg') no-repeat center;
      background-size: cover;
      height: 200px;
    }

    .logo {
      background-image: url("../assets/logo.png");
      width: 100px;
      height: 50px;
    }
  CSS

  File.write(full_path, content || default_content)
  full_path
end

def create_test_js(site, path, content = nil)
  full_path = File.join(site.source, path)
  FileUtils.mkdir_p(File.dirname(full_path))

  default_content = <<~JS
    // Test JavaScript file
    (function() {
      'use strict';

      function initializeApp() {
        console.log('App initialized');

        // Sample functionality
        const buttons = document.querySelectorAll('.btn');
        buttons.forEach(button => {
          button.addEventListener('click', handleButtonClick);
        });
      }

      function handleButtonClick(event) {
        event.preventDefault();
        console.log('Button clicked:', event.target);
      }

      // Initialize when DOM is ready
      if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initializeApp);
      } else {
        initializeApp();
      }
    })();
  JS

  File.write(full_path, content || default_content)
  full_path
end

def create_liquid_context(site, assigns = {})
  registers = { site: site }
  Liquid::Context.new(assigns, {}, registers)
end

def create_test_draft(site, filename, content = nil)
  drafts_dir = File.join(site.source, '_drafts')
  FileUtils.mkdir_p(drafts_dir)

  draft_path = File.join(drafts_dir, filename)

  default_content = <<~MARKDOWN
    ---
    title: Test Draft
    layout: post
    ---

    This is a test draft post with assets.

    ![Test Image]({% image_transform assets/hero.jpg[width="400"] %})

    <picture>
      <source type="image/webp" {% srcset assets/hero.jpg[format="webp"] 400 800 %}>
      <img src="{% image_transform assets/hero.jpg[width="800"] %}" alt="Hero">
    </picture>
  MARKDOWN

  File.write(draft_path, content || default_content)
  draft_path
end

def create_tag(tag_class, markup)
  # Create a proper Liquid template and parse it to get real tokens
  tag_name = case tag_class.name
  when 'Jekyll::Tags::ImageTransformTag'
    'image_transform'
  when 'Jekyll::Tags::SrcsetTag'
    'srcset'
  when 'Jekyll::Tags::AssetTag'
    'asset'
  else
    'test_tag'
  end

  # Create a simple liquid template to get proper tokens
  template_source = "{% #{tag_name} #{markup} %}"
  template = Liquid::Template.parse(template_source)

  # Extract the tag from the parsed template
  tag_node = template.root.nodelist.first
  tag_node
end
