#!/usr/bin/env node

import { existsSync, readFileSync, writeFileSync, mkdirSync, rmSync } from "node:fs"
import { execFileSync } from "node:child_process"
import { join, resolve } from "node:path"

const repoRoot = resolve(import.meta.dirname, "..", "..")
const runtimeDir = process.env.QJCLAW_SMOKE_RUNTIME_DIR || join(repoRoot, "vendor", "openclaw-runtime")

let failures = 0

function check(label, condition, detail) {
  if (condition) {
    console.log(`  PASS: ${label}`)
  } else {
    console.error(`  FAIL: ${label}${detail ? ` — ${detail}` : ""}`)
    failures++
  }
}

console.log("mac-workspace-entry-smoke: validating workspace automation via bundled Python")

const pythonExe = join(runtimeDir, "python", "bin", "python3")
const nodeExe = join(runtimeDir, "node", "bin", "node")

if (!existsSync(pythonExe)) {
  console.error(`  FATAL: python3 not found at ${pythonExe}`)
  process.exit(1)
}

// 1. Create a minimal test project
const tmpDir = join(repoRoot, ".workspace-smoke-tmp")
if (existsSync(tmpDir)) rmSync(tmpDir, { recursive: true, force: true })
mkdirSync(tmpDir, { recursive: true })

// Write project.json with Python automation
const projectJson = {
  workspaceAutomation: {
    runtime: "python",
    script: "run.py",
    args: []
  }
}
writeFileSync(join(tmpDir, "project.json"), JSON.stringify(projectJson, null, 2), "utf8")

// Write a minimal run.py that prints a known marker
const runPy = `
import sys
import json
print("QJC_WORKSPACE_EVENT\\t" + json.dumps({"type": "started", "runId": "smoke-test"}))
print("QJC_WORKSPACE_EVENT\\t" + json.dumps({"type": "completed", "content": "workspace smoke ok"}))
sys.exit(0)
`
writeFileSync(join(tmpDir, "run.py"), runPy, "utf8")

// 2. Execute Python automation script
try {
  const stdout = execFileSync(pythonExe, [join(tmpDir, "run.py")], {
    encoding: "utf8",
    timeout: 15000,
    cwd: tmpDir,
    env: {
      ...process.env,
      PYTHONUTF8: "1",
      PYTHONIOENCODING: "utf-8",
    }
  })
  const lines = stdout.trim().split("\n")
  const startedLine = lines.find(l => l.includes('"type": "started"'))
  const completedLine = lines.find(l => l.includes('"type": "completed"'))

  check("Python automation produced started event", Boolean(startedLine))
  check("Python automation produced completed event", Boolean(completedLine))

  if (completedLine) {
    const eventData = JSON.parse(completedLine.split("\t")[1])
    check("completed event content matches", eventData.content === "workspace smoke ok", `got: ${eventData.content}`)
  }
} catch (e) {
  check("Python automation execution", false, e.message?.split("\n")[0])
}

// 3. Test Node executable can run
if (existsSync(nodeExe)) {
  try {
    const stdout = execFileSync(nodeExe, ["-e", "console.log('node-ok')"], {
      encoding: "utf8",
      timeout: 5000,
    }).trim()
    check("Node bundled executable works", stdout === "node-ok", `got: ${stdout}`)
  } catch (e) {
    check("Node bundled executable works", false, e.message?.split("\n")[0])
  }
}

// Cleanup
rmSync(tmpDir, { recursive: true, force: true })

// Summary
console.log("")
if (failures === 0) {
  console.log("mac-workspace-entry-smoke: ALL PASSED")
} else {
  console.error(`mac-workspace-entry-smoke: ${failures} FAILURE(S)`)
  process.exit(1)
}
