/**
 * studiograph clear — clear agent sessions and/or memory
 *
 * Local mode (default): wipes `~/.studiograph/sessions/` and `/memory/` on
 * this machine. Remote mode (`--remote <url>`): POSTs to `/api/clear` on a
 * deployed server, which scopes the wipe to the authed user's per-user
 * directory only.
 */
import { Command } from 'commander';
import { existsSync, readdirSync, rmSync } from 'fs';
import { join } from 'path';
import { homedir } from 'os';
import { text, password as passwordPrompt, log } from '@clack/prompts';
import { getStudiographToken, setStudiographToken, clearStudiographToken } from '../../core/user-config.js';
const STUDIOGRAPH_DIR = join(homedir(), '.studiograph');
function clearDir(dirPath, ext) {
    if (!existsSync(dirPath))
        return 0;
    const files = readdirSync(dirPath).filter(f => f.endsWith(ext));
    for (const f of files) {
        rmSync(join(dirPath, f));
    }
    return files.length;
}
export const clearCommand = new Command('clear')
    .description('Clear agent sessions, memory, or both')
    .argument('[target]', 'What to clear: sessions, memory, or all (default: all)', 'all')
    .option('--remote <url>', 'Clear on a remote Studiograph server (per-user scope)')
    .option('--reset', 'Full reset: also wipes DB state (onboarding flag, cached briefing, settings). Implies --remote and target=all.')
    .option('--token <token>', 'Personal API token for remote auth (or STUDIOGRAPH_TOKEN env)')
    .option('--email <email>', 'Email for remote auth (or STUDIOGRAPH_EMAIL env)')
    .option('--password <password>', 'Password for remote auth (or STUDIOGRAPH_PASSWORD env)')
    .action(async (target, opts) => {
    const validTargets = ['sessions', 'memory', 'all'];
    if (!validTargets.includes(target)) {
        console.error(`Invalid target "${target}". Use: ${validTargets.join(', ')}`);
        process.exit(1);
    }
    if (opts.reset) {
        if (!opts.remote) {
            console.error('--reset requires --remote (DB state lives on the server).');
            process.exit(1);
        }
        await resetRemote(opts.remote, opts);
        return;
    }
    if (opts.remote) {
        await clearRemote(opts.remote, target, opts);
        return;
    }
    if (target === 'sessions' || target === 'all') {
        const count = clearDir(join(STUDIOGRAPH_DIR, 'sessions'), '.json');
        console.log(`Cleared ${count} session${count === 1 ? '' : 's'}`);
    }
    if (target === 'memory' || target === 'all') {
        const count = clearDir(join(STUDIOGRAPH_DIR, 'memory'), '.md');
        console.log(`Cleared ${count} memory file${count === 1 ? '' : 's'}`);
    }
});
async function resetRemote(remoteUrl, opts) {
    const base = remoteUrl.replace(/\/+$/, '');
    const httpHeader = await resolveAuthHeader(base, opts);
    const res = await fetch(`${base}/api/reset`, {
        method: 'POST',
        headers: { ...httpHeader, 'Content-Type': 'application/json' },
        body: '{}',
    });
    if (!res.ok) {
        const body = await res.json().catch(() => ({}));
        console.error(`Failed: ${body.error || res.statusText}`);
        process.exit(1);
    }
    const result = await res.json();
    const c = result.cleared ?? { sessions: 0, memory: 0 };
    console.log(`Cleared ${c.sessions} session${c.sessions === 1 ? '' : 's'} and ${c.memory} memory file${c.memory === 1 ? '' : 's'} on ${base}`);
    if (result.dbStateReset) {
        console.log('Reset DB state: onboarding flag, cached briefing, settings.');
    }
}
async function clearRemote(remoteUrl, target, opts) {
    const base = remoteUrl.replace(/\/+$/, '');
    const httpHeader = await resolveAuthHeader(base, opts);
    const res = await fetch(`${base}/api/clear`, {
        method: 'POST',
        headers: { ...httpHeader, 'Content-Type': 'application/json' },
        body: JSON.stringify({ target }),
    });
    if (!res.ok) {
        const body = await res.json().catch(() => ({}));
        console.error(`Failed: ${body.error || res.statusText}`);
        process.exit(1);
    }
    const result = await res.json();
    const c = result.cleared ?? { sessions: 0, memory: 0 };
    if (target === 'sessions' || target === 'all') {
        console.log(`Cleared ${c.sessions} session${c.sessions === 1 ? '' : 's'} on ${base}`);
    }
    if (target === 'memory' || target === 'all') {
        console.log(`Cleared ${c.memory} memory file${c.memory === 1 ? '' : 's'} on ${base}`);
    }
}
/**
 * Resolve auth headers for the remote server. Mirrors the precedence used by
 * `studiograph push --remote`: explicit token → STUDIOGRAPH_TOKEN env → email
 * + password (flags or env) → stored CLI token from ~/.studiograph/user.json
 * → interactive prompts.
 */
async function resolveAuthHeader(base, opts) {
    const explicitToken = opts.token || process.env.STUDIOGRAPH_TOKEN;
    if (explicitToken) {
        return { 'Authorization': `Bearer ${explicitToken.trim()}` };
    }
    const email = opts.email || process.env.STUDIOGRAPH_EMAIL;
    const password = opts.password || process.env.STUDIOGRAPH_PASSWORD;
    if (email && password) {
        return loginForCookie(base, email, password);
    }
    const storedToken = getStudiographToken(base);
    if (storedToken) {
        const header = { 'Authorization': `Bearer ${storedToken}` };
        const probe = await fetch(`${base}/api/auth/tokens`, { headers: header }).catch(() => null);
        if (probe?.ok)
            return header;
        if (probe?.status === 401) {
            clearStudiographToken(base);
            log.info('Stored CLI token is no longer valid — signing in again.');
        }
        else if (probe) {
            return header; // non-401 → keep using it; real request will surface the error
        }
    }
    if (!process.stdin.isTTY) {
        throw new Error('No credentials provided and stdin is not a TTY. Use --token, --email + --password, or set STUDIOGRAPH_TOKEN.');
    }
    const emailPrompt = await text({ message: 'Email:', validate: (v) => v.includes('@') ? undefined : 'Enter a valid email' });
    if (typeof emailPrompt === 'symbol')
        process.exit(0);
    const passPrompt = await passwordPrompt({ message: 'Password:' });
    if (typeof passPrompt === 'symbol')
        process.exit(0);
    const emailStr = String(emailPrompt);
    const passStr = String(passPrompt);
    const httpHeader = await loginForCookie(base, emailStr, passStr);
    // Mint and persist a CLI token so subsequent runs skip the prompt.
    try {
        const mintRes = await fetch(`${base}/api/auth/tokens`, {
            method: 'POST',
            headers: { ...httpHeader, 'Content-Type': 'application/json' },
            body: JSON.stringify({ name: `cli-${process.platform}-${Date.now()}` }),
        });
        if (mintRes.ok) {
            const body = await mintRes.json();
            if (body.token) {
                setStudiographToken(base, body.token);
                log.info('Saved personal API token to ~/.studiograph/user.json for future runs');
            }
        }
    }
    catch { /* non-fatal */ }
    return httpHeader;
}
async function loginForCookie(base, email, password) {
    const loginRes = await fetch(`${base}/api/auth/login`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, password }),
    });
    if (!loginRes.ok) {
        const body = await loginRes.json().catch(() => ({}));
        throw new Error(`Login failed: ${body.error || loginRes.statusText}`);
    }
    const cookies = loginRes.headers.getSetCookie?.() ?? [];
    const tokenCookie = cookies.find(c => c.startsWith('__sg_token='));
    if (!tokenCookie) {
        throw new Error('Login succeeded but no session cookie was returned');
    }
    return { 'Cookie': tokenCookie.split(';')[0] };
}
//# sourceMappingURL=clear.js.map