import gulp from "gulp"
import { getCurrentVersion } from "../utils/getVersion.js"
import { getReleasePath, getRemoteReleaseUrl } from "../utils/paths.js"
import { getPlanFromCli } from "../utils/readCliParams.js"
import filePost from "../utils/filePost.js"
import { plans } from "../constants/plans.js"
import yargs from "yargs"
import { hideBin } from "yargs/helpers"
import { DEPLOY_TOKEN } from "../constants/tokens.js"
import { exec } from "child_process"

const deploy = (plan, done) => {
  const version = getCurrentVersion()

  if (plan.slug === "mapsvg-demo") {
    exec(
      `cd ~/WebstormProjects/demo.mapsvg.com && git add -A && git commit -m "build: ${version}" && git push`,
      (err, stdout, stderr) => {
        if (err) {
          console.error("❌ Git error:", err)
          done(err)
          return
        }
        console.log("✅ Git commit and push complete:", stdout)
        done()
      },
    )
    return
  } else if (plan.slug === "mapsvg-lite") {
    // Run the svn-sync task for lite version
    return gulp.series("svn-sync")(done)
  } else {
    return gulp.src(getReleasePath({ version, slug: plan.slug })).pipe(
      filePost({
        url: getRemoteReleaseUrl({ slug: plan.slug, version }),
        token: DEPLOY_TOKEN,
        timeout: 1000000,
      }),
    )
  }
}

const deployAll = (done) => {
  const argv = yargs(hideBin(process.argv)).argv
  const withLite = argv.withLite
  const withDemo = argv.withDemo

  const filteredPlans = plans.filter((plan) => {
    if (plan.slug === "mapsvg-lite" && !withLite) return false
    if (plan.slug === "mapsvg-demo" && !withDemo) return false
    return true
  })

  return gulp.series(...filteredPlans.map((plan) => (done) => deploy(plan, done)))(done)
}

gulp.task("deploy", function (done) {
  const currentPlan = getPlanFromCli()
  return deploy(currentPlan, done)
})

gulp.task("deploy-all", function (done) {
  return deployAll(done)
})
