import { spawnSync } from "child_process"
import path from "path"
import { tool } from "@opencode-ai/plugin"

export default tool({
  description:
    "Project status oracle. Read-only check of repo architecture conformance. Auto-detects project type (frontend→fullstack, fastapi→backend, typer→cli, aiogram→bot, prefect→worker) and runs 8 check groups: Структура, Тонкие роуты (AST ≤50 lines), Качество кода (mypy/ruff/pytest), Тесты (conftest, stub-detector, no @pytest.mark.asyncio), README (12 delimiter tags), Infra (branch protection, ci.yml, dependabot, LICENSE, pre-commit), Coverage (non-blocking), Pyproject (13 checks: build-system, hatch wheel, project fields, ruff/mypy/pytest config, coverage, pre-commit, uv.lock, requires-python vs .python-version). Issue #275: all checks are non-blocking (WARN) and the exit code is always 0 (informational mode); check=true is accepted for CLI compatibility but no longer forces exit 1; pass fast=true to skip slow/remote checks (branch protection); pass repo=<path> to check an arbitrary repo instead of the current worktree.",
  args: {
    check: tool.schema.boolean().optional().describe("Accepted for CLI compatibility — issue #275: exit code is always 0 (all checks WARN, non-blocking)"),
    fast: tool.schema.boolean().optional().describe("If true, skip slow/remote checks (branch protection via gh)"),
    repo: tool.schema.string().optional().describe("Path to repo to check (default: current worktree). Use to run against an arbitrary repo without switching cwd, e.g. project-status --repo /root/workspace/youtube-kit"),
  },
  async execute(args, context) {
    const script = path.join(import.meta.dir, "..", "scripts", "project-status.py")
    const cmdArgs: string[] = []
    if (args.check) cmdArgs.push("--check")
    if (args.fast) cmdArgs.push("--fast")
    if (args.repo) cmdArgs.push("--repo", args.repo)
    const cwd = args.repo ? path.resolve(args.repo) : context.worktree
    const r = spawnSync("python3", [script, ...cmdArgs], {
      encoding: "utf-8",
      cwd,
    })
    if (r.status === null) {
      return `⚠️ project_status failed (no exit): ${r.stderr || r.stdout}`
    }
    if (r.status !== 0 && !args.check) {
      return `⚠️ project_status failed (exit ${r.status}): ${r.stderr}`
    }
    return r.stdout.trim()
  },
})