#!/usr/bin/env node
// OneStore local setup and direct upload helper. Node.js 20+, no dependencies.
import { readFile, writeFile, mkdir, rename, lstat, unlink, stat, readdir, rmdir } from 'node:fs/promises';
import { createReadStream } from 'node:fs';
import { homedir } from 'node:os';
import { resolve, dirname, join } from 'node:path';
import { pathToFileURL } from 'node:url';
import { createHash, randomUUID } from 'node:crypto';
import { spawnSync } from 'node:child_process';

export const SKILL_FILES = ['SKILL.md', 'references/releases.md', 'references/content.md', 'references/troubleshooting.md'];
const hash = value => createHash('sha256').update(value).digest('hex');
const equal = (a, b) => JSON.stringify(a) === JSON.stringify(b);
const object = value => value && typeof value === 'object' && !Array.isArray(value);
async function read(path) { try { return await readFile(path, 'utf8'); } catch (e) { if (e.code === 'ENOENT') return null; throw e; } }
async function regular(path) {
  try { const s = await lstat(path); if (!s.isFile()) throw Error(`Expected a regular file: ${path}`); }
  catch (e) { if (e.code !== 'ENOENT') throw e; }
}
async function save(path, text) {
  await regular(path);
  await mkdir(dirname(path), { recursive: true });
  const tmp = `${path}.${randomUUID()}.tmp`;
  try { await writeFile(tmp, text, { mode: 0o600, flag: 'wx' }); await rename(tmp, path); }
  finally { await unlink(tmp).catch(e => { if (e.code !== 'ENOENT') throw e; }); }
}
export function origin(value = 'https://www.onestore.so') {
  const u = new URL(value);
  if (u.username || u.password || u.search || u.hash || u.pathname !== '/' ||
      (u.protocol !== 'https:' && !(u.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(u.hostname)))) {
    throw Error('Use an HTTPS origin without a path, query or credentials (HTTP loopback is allowed for local testing).');
  }
  return u.origin;
}
export function validateSkill(bundle) {
  if (bundle?.name !== 'use-onestore' || bundle.version !== 1 || !object(bundle.files) ||
      !equal(Object.keys(bundle.files).sort(), [...SKILL_FILES].sort()) ||
      Object.values(bundle.files).some(v => typeof v !== 'string' || v.length > 100_000)) throw Error('Invalid OneStore skill bundle.');
  return bundle;
}
export async function fetchSkill(base) {
  const response = await fetch(`${origin(base)}/mcp/skill.json`, { redirect: 'error', signal: AbortSignal.timeout(15_000) });
  if (!response.ok) throw Error(`Skill download failed (${response.status}).`);
  const body = await response.text();
  if (body.length > 400_000) throw Error('Skill bundle is too large.');
  return validateSkill(JSON.parse(body));
}
export function locations(client, scope, home = homedir(), cwd = process.cwd()) {
  if (!['cursor', 'claude', 'codex'].includes(client)) throw Error('Choose --client cursor, claude or codex.');
  if (!['user', 'project'].includes(scope)) throw Error('Choose --scope user or project.');
  if (client === 'codex' && scope !== 'user') throw Error('Codex setup supports user scope; use its documented config for trusted project scope.');
  const root = scope === 'user' ? home : cwd;
  const skillRoot = client === 'codex' ? join(home, '.agents', 'skills') : join(root, `.${client}`, 'skills');
  return {
    skill: join(skillRoot, 'use-onestore'),
    config: client === 'cursor' ? join(root, '.cursor', 'mcp.json') : client === 'claude' ? join(root, scope === 'user' ? '.claude.json' : '.mcp.json') : null,
  };
}
function codex(args) {
  // Adding a server may start the client's OAuth flow. Let the user interact
  // with that flow instead of hiding its output or timing out after a config write.
  const interactive = args[1] === 'add';
  const result = spawnSync('codex', args, { encoding: 'utf8', stdio: interactive ? 'inherit' : 'pipe', ...(interactive ? {} : { timeout: 30_000 }), windowsHide: true });
  if (result.error || result.status !== 0) throw Error('Codex command failed. Check that codex is installed and its configuration is valid.');
  return result.stdout;
}
async function currentConfig(path) {
  const raw = await read(path);
  const data = raw === null ? {} : JSON.parse(raw);
  if (!object(data) || (data.mcpServers !== undefined && !object(data.mcpServers))) throw Error('Invalid MCP configuration; no changes made.');
  return { raw, data };
}
async function writeConfig(path, before, data) {
  if (await read(path) !== before) throw Error('Configuration changed during setup. Run setup again.');
  if (before !== null) await writeFile(`${path}.onestore-${randomUUID()}.bak`, before, { mode: 0o600, flag: 'wx' });
  await save(path, JSON.stringify(data, null, 2) + '\n');
}
export async function setup({ client, scope = 'user', base, home, cwd, bundle, runCodex = codex }) {
  const endpoint = `${origin(base)}/api/mcp`;
  const paths = locations(client, scope, home, cwd);
  validateSkill(bundle);
  const markerPath = join(paths.skill, '.onestore-install.json');
  const markerText = await read(markerPath);
  const marker = markerText ? JSON.parse(markerText) : null;
  if (marker && (marker.endpoint !== endpoint || marker.client !== client || marker.scope !== scope)) throw Error('Existing skill belongs to a different installation. Uninstall it first.');
  // Preflight every managed file before touching configuration or local skills.
  for (const file of SKILL_FILES) {
    const path = join(paths.skill, file);
    await regular(path);
    const previous = await read(path);
    if (previous !== null && (!marker || marker.hashes?.[file] !== hash(previous))) throw Error(`Preserving existing or edited skill: ${path}`);
  }
  let ownsConfig = marker?.ownsConfig ?? false;
  const entry = client === 'claude' ? { type: 'http', url: endpoint } : { url: endpoint };
  if (paths.config) {
    const { raw, data } = await currentConfig(paths.config);
    const existing = data.mcpServers?.onestore;
    if (existing && !equal(existing, entry)) throw Error('An existing onestore entry differs. Update it manually or remove it before setup.');
    if (!existing) {
      await writeConfig(paths.config, raw, { ...data, mcpServers: { ...data.mcpServers, onestore: entry } });
      ownsConfig = true;
    }
  } else {
    const servers = JSON.parse(runCodex(['mcp', 'list', '--json']));
    if (!Array.isArray(servers)) throw Error('Unsupported Codex configuration output.');
    const existing = servers.find(s => s.name === 'onestore');
    if (existing && existing.transport?.url !== endpoint) throw Error('Existing Codex onestore server uses a different URL.');
    if (!existing) { runCodex(['mcp', 'add', 'onestore', '--url', endpoint]); ownsConfig = true; }
  }
  for (const file of SKILL_FILES) await save(join(paths.skill, file), bundle.files[file]);
  await save(markerPath, JSON.stringify({ endpoint, client, scope, ownsConfig, hashes: Object.fromEntries(SKILL_FILES.map(file => [file, hash(bundle.files[file])])) }, null, 2));
  return paths;
}
export async function uninstall({ client, scope = 'user', base, home, cwd, runCodex = codex }) {
  const paths = locations(client, scope, home, cwd);
  const markerPath = join(paths.skill, '.onestore-install.json');
  const markerText = await read(markerPath);
  if (!markerText) throw Error('No managed installation found. Remove the MCP entry/skill manually if installed by another method.');
  const marker = JSON.parse(markerText);
  const endpoint = `${origin(base)}/api/mcp`;
  if (marker.endpoint !== endpoint || marker.client !== client || marker.scope !== scope) throw Error('Installation does not match these options.');
  for (const file of SKILL_FILES) {
    await regular(join(paths.skill, file));
    const value = await read(join(paths.skill, file));
    if (value !== null && hash(value) !== marker.hashes?.[file]) throw Error(`Preserving edited skill: ${file}`);
  }
  if (marker.ownsConfig && paths.config) {
    const { raw, data } = await currentConfig(paths.config);
    const expected = client === 'claude' ? { type: 'http', url: endpoint } : { url: endpoint };
    if (data.mcpServers?.onestore && !equal(data.mcpServers.onestore, expected)) throw Error('MCP configuration changed; remove it manually.');
    if (data.mcpServers?.onestore) { delete data.mcpServers.onestore; await writeConfig(paths.config, raw, data); }
  } else if (marker.ownsConfig) {
    const servers = JSON.parse(runCodex(['mcp', 'list', '--json']));
    const current = servers.find(s => s.name === 'onestore');
    if (current && current.transport?.url !== endpoint) throw Error('Codex server changed; remove it manually.');
    if (current) runCodex(['mcp', 'remove', 'onestore']);
  }
  for (const file of SKILL_FILES) await unlink(join(paths.skill, file)).catch(e => { if (e.code !== 'ENOENT') throw e; });
  await unlink(markerPath);
  for (const path of [join(paths.skill, 'references'), paths.skill]) {
    if ((await readdir(path).catch(e => { if (e.code === 'ENOENT') return ['missing']; throw e; })).length === 0) await rmdir(path);
  }
}
export async function doctor(base) {
  const expected = `${origin(base)}/api/mcp`;
  const response = await fetch(`${origin(base)}/.well-known/oauth-protected-resource/api/mcp`, { redirect: 'error', signal: AbortSignal.timeout(15_000) });
  if (!response.ok) throw Error(`Discovery failed (${response.status}).`);
  const info = await response.json();
  if (info.resource !== expected || !info.authorization_servers?.includes(origin(base))) throw Error('OAuth discovery does not match the chosen origin. Check APP_URL.');
  const auth = await fetch(`${origin(base)}/.well-known/oauth-authorization-server`, { redirect: 'error', signal: AbortSignal.timeout(15_000) });
  if (!auth.ok) throw Error(`Authorization discovery failed (${auth.status}).`);
  const metadata = await auth.json();
  if (metadata.issuer !== origin(base) || !metadata.code_challenge_methods_supported?.includes('S256')) throw Error('Expected OAuth issuer and PKCE S256 support.');
  return 'Public OAuth discovery is healthy. In your AI client, authenticate and call get_connection + list_apps to verify actual access.';
}
export async function upload(file, signedUrl, contentType = 'application/octet-stream') {
  const url = new URL(signedUrl.trim());
  if (url.username || url.password || url.hash || (url.protocol !== 'https:' && !(url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname)))) throw Error('Expected an HTTPS signed upload URL.');
  if (!['application/octet-stream', 'image/png', 'image/jpeg'].includes(contentType)) throw Error('Unsupported content type.');
  const info = await stat(file);
  if (!info.isFile() || info.size < 1 || info.size > 500 * 1024 * 1024) throw Error('Expected a nonempty file up to 500 MiB.');
  const stream = createReadStream(file);
  try {
    const response = await fetch(url, { method: 'PUT', body: stream, duplex: 'half', redirect: 'error', signal: AbortSignal.timeout(30 * 60_000), headers: { 'Content-Type': contentType, 'Content-Length': String(info.size) } });
    await response.body?.cancel();
    if (!response.ok) throw Error(`Upload failed (${response.status}). Do not finalize.`);
    return { uploadedBytes: info.size, next: 'Run finalize_upload (or finalize_asset_upload) through the same OneStore MCP connection.' };
  } catch (e) {
    // Fetch/stream errors can embed the signed URL; never surface them verbatim.
    if (/^Upload failed \(\d+\)/.test(e.message)) throw e;
    throw Error('Upload interrupted or rejected. Do not finalize; check the URL expiry and prepare a new upload if needed.');
  } finally { stream.destroy(); }
}
function parse(args) {
  const [command = 'help', ...rest] = args;
  const options = {};
  for (let i = 0; i < rest.length; i += 2) {
    const key = rest[i];
    if (!['--client', '--scope', '--origin', '--file', '--content-type'].includes(key) || !rest[i + 1] || rest[i + 1].startsWith('--')) throw Error('Invalid option. Run with help for usage.');
    options[key.slice(2)] = rest[i + 1];
  }
  return { command, options };
}
export async function main(args = process.argv.slice(2)) {
  const { command, options } = parse(args);
  const base = origin(options.origin);
  if (command === 'help') return console.log(`OneStore • Node.js 20+\nsetup --client cursor|claude|codex [--scope user|project] [--origin https://www.onestore.so]\nuninstall --client cursor|claude|codex [same scope/origin]\ndoctor [--origin https://www.onestore.so]\nupload --file /path/app.aab [--content-type application/octet-stream]\nUpload reads the signed URL from stdin. No tokens or credentials are stored.\nSetup updates only OneStore files; edited files are preserved. Re-run setup to update.\nCodex setup uses its installed CLI and user scope. ChatGPT/Claude web use a remote connector.\nUninstall removes local managed files; revoke the connection in OneStore to invalidate access.`);
  if (command === 'doctor') return console.log(await doctor(base));
  if (command === 'upload') {
    if (!options.file) throw Error('Provide --file.');
    if (process.stdin.isTTY) throw Error('Pass the signed URL on stdin from a private file or program; do not include it in shell history.');
    let input = ''; for await (const chunk of process.stdin) { input += chunk; if (input.length > 16_384) throw Error('Upload URL input is too large.'); }
    return console.log(JSON.stringify(await upload(options.file, input, options['content-type'])));
  }
  const config = { client: options.client, scope: options.scope ?? 'user', base };
  locations(config.client, config.scope); // Validate before downloading.
  if (command === 'setup') {
    const paths = await setup({ ...config, bundle: await fetchSkill(base) });
    console.log(`MCP configured; skill installed at ${paths.skill}.`);
    console.log(config.client === 'codex' ? 'Run: codex mcp login onestore' : config.client === 'claude' ? 'Open Claude Code, run /mcp and authenticate OneStore.' : 'Open Cursor MCP settings and authenticate OneStore.');
    console.log('Choose your workspace, apps, permissions and autonomy in OneStore. Then ask: List my accessible OneStore apps.');
  } else if (command === 'uninstall') {
    await uninstall(config);
    console.log(`Managed local installation removed. Revoke the connection at ${base}/app/settings to invalidate access.`);
  } else throw Error('Unknown command. Run with help.');
}
if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
  main().catch(error => { console.error(error.message); process.exitCode = 1; });
}
