import { spawn } from 'node:child_process';
import os from 'node:os';
import fs from 'node:fs';
import path from 'node:path';
import { requireFreshMembership, requireSession } from '@/lib/auth.js';
import { requireRole } from '@/lib/authz.js';
import { approveMinesImportRoot } from '@/lib/mines/import-roots.js';

export const dynamic = 'force-dynamic';
export const runtime = 'nodejs';

function runDialog(cmd, args) {
  return new Promise((resolve, reject) => {
    const child = spawn(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'] });
    let out = '';
    let err = '';
    const timer = setTimeout(() => { try { child.kill('SIGTERM'); } catch {} reject(new Error('picker timeout')); }, 120000);
    child.stdout.on('data', (d) => { out += d.toString(); });
    child.stderr.on('data', (d) => { err += d.toString(); });
    child.on('error', (e) => { clearTimeout(timer); reject(e); });
    child.on('close', (code) => {
      clearTimeout(timer);
      if (code === 0) resolve(out.trim());
      else reject(new Error((err || `exit ${code}`).trim()));
    });
  });
}

function appleScriptString(value) {
  return String(value || '').replace(/\\/g, '\\\\').replace(/"/g, '\\"');
}

async function requireAdmin(request) {
  const session = await requireSession(request);
  await requireFreshMembership(session, session.org_id);
  requireRole(session, 'admin', session.org_id);
  return session;
}

function authError(err) {
  if (err && typeof err === 'object' && err.status) {
    return Response.json({ error: err.error || 'unauthorized' }, { status: err.status });
  }
  throw err;
}

export async function POST(request) {
  let session;
  try {
    session = await requireAdmin(request);
  } catch (err) {
    return authError(err);
  }

  const body = await request.json().catch(() => ({}));
  const title = String(body.title || 'Select a folder').replace(/["\\]/g, '');
  const startPath = String(body.start_path || os.homedir() || '/').trim();
  const registerImportRoot = Boolean(body.register_import_root);

  try {
    let picked;
    if (process.platform === 'darwin') {
      const script = `set chosen to POSIX path of (choose folder with prompt "${appleScriptString(title)}" default location POSIX file "${appleScriptString(startPath)}")\nreturn chosen`;
      const raw = await runDialog('osascript', ['-e', script]);
      picked = raw.trim();
    } else if (process.platform === 'linux') {
      try {
        const raw = await runDialog('zenity', ['--file-selection', '--directory', `--title=${title}`, `--filename=${startPath}/`]);
        picked = raw.trim();
      } catch {
        return Response.json({ error: 'zenity not installed; install zenity or paste path manually' }, { status: 501 });
      }
    } else {
      return Response.json({ error: `native folder picker not supported on ${process.platform}; paste path manually` }, { status: 501 });
    }

    if (!picked) return Response.json({ error: 'no folder chosen' }, { status: 400 });
    if (!fs.existsSync(picked)) return Response.json({ error: 'chosen folder does not exist' }, { status: 400 });
    const stat = fs.statSync(picked);
    if (!stat.isDirectory()) return Response.json({ error: 'path is not a folder' }, { status: 400 });

    const folderPath = path.normalize(picked);
    let approved_import_root = null;
    if (registerImportRoot) {
      approved_import_root = approveMinesImportRoot(folderPath, {
        label: body.label || 'Selected Mines import folder',
        user_id: session.user_id,
        org_id: session.org_id,
        acting_on_behalf_of_user_id: session.user_id,
      });
      if (approved_import_root.status !== 'ok') {
        return Response.json({ folder_path: folderPath, error: approved_import_root.error }, { status: 400 });
      }
    }

    return Response.json({ folder_path: folderPath, approved_import_root });
  } catch (err) {
    const msg = String(err?.message || err);
    if (/User canceled|user cancelled|-128/i.test(msg)) return Response.json({ error: 'cancelled' }, { status: 499 });
    return Response.json({ error: msg }, { status: 500 });
  }
}
