const fs = require('fs');
const path = require('path');

/**
 * Claude Code Cloud adapter.
 *
 * Generates a routine config file under `.claude/routines/<name>.json` that
 * Claude Code Cloud can pick up via `/schedule` or the RemoteTrigger mechanism.
 *
 * The actual remote trigger creation is interactive (user must run `/schedule`
 * inside Claude Code). The adapter writes the config and prints the exact
 * command the user needs to run.
 */
class ClaudeCodeCloudAdapter {
  constructor(cwd = process.cwd()) {
    this.cwd = cwd;
  }

  get name() { return 'claude-code-cloud'; }
  get label() { return 'Claude Code Cloud (RemoteTrigger)'; }
  get description() {
    return 'Schedules the agent via Claude Code Cloud RemoteTrigger. Best when you already use Claude Code Cloud.';
  }

  configDir() {
    return path.join(this.cwd, '.claude', 'routines');
  }

  configPath(name) {
    return path.join(this.configDir(), `${name}.json`);
  }

  install(spec) {
    if (!fs.existsSync(this.configDir())) {
      fs.mkdirSync(this.configDir(), { recursive: true });
    }
    const config = {
      $schema: 'baldart-routine-config-v1',
      name: spec.name,
      description: spec.description,
      schedule: spec.schedule,
      agent: spec.agent,
      prompt: spec.prompt,
      output: spec.output,
      backend: this.name,
      // Marks this as an unattended (no-human) run. Autonomy-aware skills
      // (e.g. /baldart-update) auto-detect this and drop their chat
      // confirmations, with safe guardrails (STOP on custom divergence /
      // conflicts, never forces a destructive merge). Best-effort for this
      // backend: RemoteTrigger must surface `env` into the run environment for
      // the runtime probe to see it; github-actions / cron inject it directly.
      env: { BALDART_AUTONOMOUS: '1' },
      installed_at: new Date().toISOString()
    };
    fs.writeFileSync(this.configPath(spec.name), JSON.stringify(config, null, 2) + '\n');
    // review_engine: codex is cron-only — the RemoteTrigger config schema does not carry it and the
    // cloud runner is not guaranteed to have the Codex plugin/auth — so this backend always uses claude.
    const codexWarn = String(spec.review_engine || '').toLowerCase() === 'codex'
      ? [`⚠ review_engine: codex is NOT supported on claude-code-cloud — this routine runs on the claude engine.`]
      : [];
    return {
      backend: this.name,
      artifacts: [path.relative(this.cwd, this.configPath(spec.name))],
      followup: [
        ...codexWarn,
        `Open Claude Code in this repo and run:`,
        `  /schedule create --config .claude/routines/${spec.name}.json`,
        `(or invoke the agent once with /loop ${spec.schedule.cron} <command> to test the cadence)`
      ]
    };
  }

  uninstall(name) {
    const p = this.configPath(name);
    if (fs.existsSync(p)) fs.unlinkSync(p);
    return {
      backend: this.name,
      followup: [
        `Open Claude Code and run:`,
        `  /schedule delete ${name}`,
        `to remove the remote trigger.`
      ]
    };
  }

  detect(name) {
    return fs.existsSync(this.configPath(name));
  }
}

module.exports = ClaudeCodeCloudAdapter;
