import "../../Fastfile"

default_platform(:mac)


platform :mac do
  # Authenticate with Apple Store
  private_lane :authenticate_apple_store do
    app_store_connect_api_key(
      key_id: ENV["ASC_KEY_ID"],
      issuer_id: ENV["ASC_ISSUER_ID"],
      key_content: ENV["ASC_KEY_P8_BASE64"],
      is_key_content_base64: true,
      in_house: false
    )

  end

  # Build macOS app
  lane :build_mac do
    verify_env(envs: [
      "ASC_KEY_ID",
      "ASC_ISSUER_ID",
      "ASC_KEY_P8_BASE64",
      "APP_BUNDLE_ID",
      "MATCH_PASSWORD",
      "MATCH_GIT_BASIC_AUTHORIZATION",
    ])

    authenticate_apple_store

    # Sync certificates and profiles using match
    UI.message("Syncing certificates and profiles")
    
    if is_ci
      create_keychain(
        name: "fastlane_tmp_keychain",
        password: "temp_password",
        default_keychain: true,
        unlock: true,
        timeout: 3600,
        add_to_search_list: true
      )
    end
    
    # Default to developer_id for direct distribution
    cert_type = ENV["CERT_TYPE"] || "developer_id"
    
    sync_code_signing(
      type: cert_type,
      platform: "macos",
      readonly: is_ci,
      keychain_name: is_ci ? "fastlane_tmp_keychain" : "login.keychain",
      keychain_password: is_ci ? "temp_password" : nil,
      additional_cert_types: ["mac_installer_distribution"]
    )
    
    commit = last_git_commit
    puts "*** Starting macOS release for commit(#{commit[:abbreviated_commit_hash]}) ***"

    fetch_dependencies
    
    # Build macOS app
    sh_on_root(command: "flutter build macos --release --dart-define=isAppStore=true")
    
    # Package for Mac App Store
    build_mac_app(
      skip_package_pkg: false,
      archive_path: "../build/macos/Build/Products/Release/Runner.xcarchive",
      export_method: "app-store",
      export_options: {
        teamID: "28W956D5K8"
      }
    )
  end


  desc "Release a new build to Mac App Store"
  lane :release_app_store do |options|
    # Set environment for App Store build
    ENV["CERT_TYPE"] = "appstore"
    
    build_mac

    upload_to_app_store(
      platform: "osx",
      skip_screenshots: true,
      skip_metadata: true,
      precheck_include_in_app_purchases: false,
      pkg: "./Anx Reader.pkg"
    )
  end
  
  desc "Build and notarize for direct distribution"
  lane :release_direct do |options|
    # Set environment for Developer ID build  
    ENV["CERT_TYPE"] = "developer_id"
    
    build_mac
    
    # Notarize the app
    notarize(
      package: "../build/macos/Build/Products/Release/Runner.app"
    )
  end
end
