#!/usr/bin/env ruby
# frozen_string_literal: true

require "bundler/setup"
require "optparse"
require "DYXCFrameworkBuilder"

class BuilderCLI
  def initialize
    @options = {}
    @parser = create_option_parser
  end

  def run
    begin
      @parser.parse!(into: @options)

      # 只有当没有特殊命令处理时才调用XCFrameworkBuilder
      # 特殊命令在option回调中处理并exit，不会到达这里
      DYXCFrameworkBuilder::XCFrameworkBuilder.new(@options).build

    rescue SystemExit
      # 允许正常的exit调用通过
      raise
    rescue OptionParser::InvalidOption, OptionParser::MissingArgument => e
      puts "Error: #{e.message}"
      puts @parser
      exit 1
    rescue => e
      puts "Error: #{e.message}"
      exit 1
    end
  end

  private

  def create_option_parser
    OptionParser.new do |opts|
      opts.banner = "Usage: xcbuilder [options]"

      opts.on("-f", "--config FILE", "YAML configuration file path") do |file|
        @options[:config_path] = file
      end

      opts.on("-p", "--project PATH", "Project path") do |path|
        @options[:project_path] = path
      end

      opts.on("-t", "--target TARGET", "Target name") do |target|
        @options[:target] = target
      end

      opts.on("-c", "--configuration CONFIG", "Build configuration (Debug/Release)") do |config|
        @options[:configuration] = config
      end

      opts.on("-o", "--output OUTPUT", "Output directory") do |output|
        @options[:output_dir] = output
      end

      opts.on("-s", "--sdk SDK", "SDK (iphoneos/iphonesimulator)") do |sdk|
        @options[:sdk] = sdk
      end

      opts.on("-v", "--verbose", "Verbose output") do
        @options[:verbose] = true
      end

      opts.on("--create-config FILE", "Create configuration template file") do |file|
        DYXCFrameworkBuilder::XCFrameworkBuilder.create_config_template(file)
        puts "Configuration template created at: #{file}"
        puts "Please edit the configuration file and run with -f option"
        exit
      end

      opts.on("--from-podspec PODSPEC", "Generate configuration from .podspec file") do |podspec|
        config_path = DYXCFrameworkBuilder::XCFrameworkBuilder.generate_config_from_podspec(podspec)
        puts ""
        puts "You can now build with:"
        puts "  xcbuilder -f #{config_path} -v"
        exit
      end

      opts.on("--from-podspec-build PODSPEC", "Generate configuration and build XCFramework automatically") do |podspec|
        DYXCFrameworkBuilder::XCFrameworkBuilder.generate_config_from_podspec(podspec, nil, true)
        exit
      end

      opts.on("--from-podspec-publish PODSPEC", "Generate, build, and publish XCFramework to private repository") do |podspec|
        DYXCFrameworkBuilder::XCFrameworkBuilder.generate_config_from_podspec(podspec, nil, true, true)
        exit
      end

            opts.on("--generate-framework-podspec PODSPEC", "Generate framework podspec only (without building)") do |podspec|
        begin
          parser = DYXCFrameworkBuilder::PodspecParser.new(podspec)
          xcframework_path = File.join(parser.output_directory, parser.framework_name)

          framework_info = DYXCFrameworkBuilder::FrameworkPodspecGenerator.generate_from_original(
            parser,
            xcframework_path
          )

          puts ""
          puts "🎉 Framework podspec generated successfully!"
          puts "📄 File: #{framework_info[:path]}"
          puts "📦 Name: #{framework_info[:name]}"
          puts "🔢 Version: #{framework_info[:version]}"
          puts "🌐 Source: #{framework_info[:download_url]}"
          puts ""
          puts "💡 You can now:"
          puts "  1. Upload the XCFramework to: #{framework_info[:download_url].sub('@', '')}"
          puts "  2. Publish the podspec: pod repo push ios-specs #{framework_info[:path]}"
        rescue => e
          puts "❌ Error: #{e.message}"
          exit 1
        end
        exit
      end

      opts.on("--from-podspec-oss PODSPEC", "Generate, build, upload to OSS, and generate framework podspec") do |podspec|
        DYXCFrameworkBuilder::XCFrameworkBuilder.generate_config_from_podspec(podspec, nil, true, false, true)
        exit
      end

      opts.on("--from-podspec-auto PODSPEC", "Complete auto workflow: build XCFramework, upload to OSS, generate podspec, and publish to private repo") do |podspec|
        DYXCFrameworkBuilder::XCFrameworkBuilder.generate_config_from_podspec(podspec, nil, true, false, true, true)
        exit
      end

      opts.on("--test-oss-upload XCFRAMEWORK_PATH", "Test OSS upload with existing XCFramework") do |xcframework_path|
        begin
          # 验证 XCFramework 路径
          unless File.exist?(xcframework_path)
            puts "❌ Error: XCFramework not found at: #{xcframework_path}"
            exit 1
          end

          # 从路径提取框架名称和模拟版本
          framework_name = File.basename(xcframework_path, '.xcframework')
          test_version = "test_#{Time.now.strftime('%Y%m%d_%H%M%S')}"

          puts "🧪 Testing OSS upload functionality..."
          puts "📦 Framework: #{framework_name}"
          puts "🔢 Test Version: #{test_version}"
          puts "📁 XCFramework Path: #{xcframework_path}"
          puts "="*60

          # 执行 OSS 上传测试
          uploader = DYXCFrameworkBuilder::OSSUploader.new
          result = uploader.upload_xcframework(
            xcframework_path,
            framework_name,
            test_version
          )

          if result[:success]
            puts ""
            puts "🎉 OSS upload test completed successfully!"
            puts "🌐 Download URL: #{result[:download_url]}"
            puts "📊 File Size: #{(result[:file_size] / 1024.0 / 1024.0).round(2)} MB"
            puts "📂 OSS Path: #{result[:oss_path]}"
          else
            puts ""
            puts "❌ OSS upload test failed!"
            puts "🔍 Error: #{result[:error]}"
            exit 1
          end

        rescue => e
          puts "❌ Test failed with error: #{e.message}"
          puts "🔍 Please check your OSS configuration and network connection."
          exit 1
        end
        exit
      end

      opts.on("-h", "--help", "Show this help message") do
        puts opts
        puts ""
        puts "Examples:"
        puts "  # Create a configuration template"
        puts "  xcbuilder --create-config build_config.yml"
        puts ""
        puts "  # Generate configuration from .podspec file"
        puts "  xcbuilder --from-podspec MyLibrary.podspec"
        puts ""
        puts "  # Generate configuration and build XCFramework automatically"
        puts "  xcbuilder --from-podspec-build MyLibrary.podspec"
        puts ""
        puts "  # Complete workflow: generate, build, and publish to private repository"
        puts "  xcbuilder --from-podspec-publish MyLibrary.podspec"
        puts ""
        puts "  # Generate framework podspec only (for manual upload and publish)"
        puts "  xcbuilder --generate-framework-podspec MyLibrary.podspec"
        puts ""
        puts "  # Generate, build, upload to OSS, and generate framework podspec"
        puts "  xcbuilder --from-podspec-oss MyLibrary.podspec"
        puts ""
        puts "  # Complete auto workflow: build XCFramework, upload to OSS, generate podspec, and publish to private repo"
        puts "  xcbuilder --from-podspec-auto MyLibrary.podspec"
        puts ""
        puts "  # Test OSS upload with existing XCFramework"
        puts "  xcbuilder --test-oss-upload ./build/MyLibrary.xcframework"
        puts ""
        puts "  # Build using configuration file"
        puts "  xcbuilder -f build_config.yml -v"
        puts ""
        puts "  # Build with direct parameters"
        puts "  xcbuilder -p MyProject.xcodeproj -t MyTarget -o ./output"
        exit
      end

      opts.on("--version", "Show version") do
        puts "DYXCFrameworkBuilder version #{DYXCFrameworkBuilder::VERSION}"
        exit
      end
    end
  end
end

if __FILE__ == $0
  # 全量
  # ARGV << '--from-podspec-auto' << '/Users/leigeng/Desktop/diyi/Module/DYBase/DYBase.podspec' << '-v' if ARGV.empty?
  # 仅生成 Framework Podspec 文件：**
  # ARGV << '--generate-framework-podspec' << '/Users/leigeng/Desktop/diyi/Module/DYBase/DYBase.podspec' << '-v' if ARGV.empty?
  # 全部流程
  # ARGV << '--from-podspec-auto' << '/Users/leigeng/Desktop/diyi/Module/DYBase/DYBase.podspec' << '-v' if ARGV.empty?
  BuilderCLI.new.run
end
