/**
 * `spectral bind` — link the current directory to an Aexol Studio project.
 *
 * Usage:
 *   spectral bind <project-id> [--team-id <id>] [--name <name>] [--force]
 *
 * Writes `.aexol/aexol.jsonc` so that `spectral` knows which Studio project
 * this repository belongs to. By default it refuses to overwrite an existing
 * binding; pass `--force` to rebind.
 */
import pc from "picocolors";
import { readStudioBinding, writeStudioBinding, } from "../studio-binding.js";
export async function runBind(args) {
    // ---- Parse args ----------------------------------------------------------
    let projectId = "";
    let teamId;
    let name;
    let force = false;
    for (let i = 0; i < args.length; i++) {
        const a = args[i];
        if (a === "--team-id") {
            const next = args[i + 1];
            if (!next) {
                process.stderr.write(pc.red("--team-id requires a value\n"));
                process.exit(1);
            }
            teamId = next;
            i++;
        }
        else if (a.startsWith("--team-id=")) {
            teamId = a.slice("--team-id=".length);
        }
        else if (a === "--name") {
            const next = args[i + 1];
            if (!next) {
                process.stderr.write(pc.red("--name requires a value\n"));
                process.exit(1);
            }
            name = next;
            i++;
        }
        else if (a.startsWith("--name=")) {
            name = a.slice("--name=".length);
        }
        else if (a === "--force") {
            force = true;
        }
        else if (a.startsWith("-")) {
            process.stderr.write(pc.red(`Unknown flag: ${a}\n`));
            process.exit(1);
        }
        else if (!projectId) {
            projectId = a;
        }
        else {
            process.stderr.write(pc.red(`Unexpected argument: ${a}\n`));
            process.exit(1);
        }
    }
    if (!projectId) {
        process.stderr.write(pc.red("Usage: spectral bind <project-id> [--team-id <id>] [--name <name>] [--force]\n"));
        process.exit(1);
    }
    // ---- Check existing ------------------------------------------------------
    let existing = null;
    try {
        existing = await readStudioBinding();
    }
    catch (err) {
        const msg = err instanceof Error ? err.message : String(err);
        process.stderr.write(pc.red(`Failed to read existing binding: ${msg}\n`));
        process.exit(1);
    }
    if (existing && !force) {
        const existingName = existing.name ?? "(unnamed)";
        process.stderr.write(pc.yellow(`Already bound to project ${existingName} (${existing.projectId}). Use --force to rebind.\n`));
        process.exit(0);
    }
    // ---- Write ---------------------------------------------------------------
    const binding = {
        $schema: "https://aexol.ai/schemas/studio-binding.json",
        projectId,
        ...(teamId ? { teamId } : {}),
        ...(name ? { name } : {}),
    };
    try {
        await writeStudioBinding(binding);
    }
    catch (err) {
        const msg = err instanceof Error ? err.message : String(err);
        process.stderr.write(pc.red(`Failed to write binding: ${msg}\n`));
        process.exit(1);
    }
    const displayName = name ?? projectId;
    process.stdout.write(pc.green(`✓ Bound to Studio project: ${displayName} (${projectId})\n`));
}
