# Copyright (c) Toss.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.

require 'json'
require 'pathname'


def use_brick_modules!(app_path: nil)
  if app_path.nil? || app_path.empty?
    raise "[Brick] app_path is required. Call use_brick_modules!(app_path: '<path to your app root>')"
  end
  brick_root = app_path

  # Validate package.json exists in app_path
  package_json_path = File.join(brick_root, 'package.json')
  unless File.exist?(package_json_path)
    raise "[Brick] package.json not found at #{brick_root}. Please pass a valid app_path."
  end
  
  begin
    # Determine output path first
    ios_brick_path = get_brick_ios_path(brick_root)
    brick_codegen_pod_path = if Pathname.new(ios_brick_path).absolute?
      ios_brick_path
    else
      File.expand_path(File.join(brick_root, ios_brick_path))
    end
    brick_codegen_podspec_path = File.join(
      brick_codegen_pod_path,
      'BrickCodegen.podspec'
    )
    brick_codegen_pod_relative_path = relative_pod_path(
      brick_codegen_pod_path,
      podfile_dir
    )

    # Run brick-codegen with real-time output and colors (iOS only)
    exit_status = system("cd #{brick_root} && FORCE_COLOR=1 npx brick-codegen --platform ios --projectRoot \"#{brick_root}\"")

    unless exit_status
      raise "[Brick] brick-codegen failed. Aborting pod install. Try: (cd #{brick_root} && npx brick-codegen --platform ios --debug)"
    end

    # Require podspec to exist after successful codegen
    unless File.exist?(brick_codegen_podspec_path)
      raise "[Brick] BrickCodegen.podspec not found at #{brick_codegen_pod_path} after codegen"
    end

    # Link generated BrickCodegen pod
    pod 'BrickCodegen', :path => brick_codegen_pod_relative_path
    Pod::UI.puts "[Brick] Linked BrickCodegen from #{brick_codegen_pod_relative_path}"
  rescue => e
    # Re-raise so CocoaPods fails the install
    raise e
  end
end


def get_brick_ios_path(project_root)
  # Read brick.json from the explicit project root
  brick_config_path = File.join(project_root, 'brick.json')
  
  if File.exist?(brick_config_path)
    begin
      config = JSON.parse(File.read(brick_config_path))
      ios_path = config.dig('output', 'ios')
      if ios_path && !ios_path.empty?
        if Pathname.new(ios_path).absolute?
          Pod::UI.warn "[Brick] Using absolute path for iOS output is not recommended: #{ios_path}"
          return ios_path
        else
          return File.expand_path(File.join(project_root, ios_path))
        end
      end
    rescue => e
      Pod::UI.warn "[Brick] Failed to parse brick.json: #{e.message}"
    end
  end
  
  return File.expand_path(File.join(project_root, 'ios/.brick'))
end

def podfile_dir
  podfile_path = Pod::Config.instance.podfile_path
  return Pathname.new(Dir.pwd).expand_path if podfile_path.nil?

  podfile_path.dirname.expand_path
end

def relative_pod_path(target_path, base_dir)
  Pathname.new(target_path)
    .expand_path
    .relative_path_from(base_dir)
    .to_s
rescue ArgumentError
  target_path
end
