#!/usr/bin/env node
/**
 * mailx-send CLI — queue and send email.
 *
 * Queue management (process queued .ltr files):
 *   mailx-send --process              Process all account queues now
 *   mailx-send --process -q gmail     Process only the gmail queue
 *   mailx-send --status               Show queue status
 *
 * Create and queue a new message:
 *   mailx-send --new --to addr --subject "text" --body "text"
 *   mailx-send --new -q gmail --from "Bob <bob@gmail.com>" --to addr --subject "text"
 *   mailx-send --new --json message.json       Read message from JSON file
 *   echo '{"to":["a@b.com"],...}' | mailx-send --new --json -    Read from stdin
 *
 * JSON message format:
 *   { "to": ["addr"], "cc": ["addr"], "from": "Name <addr>",
 *     "subject": "text", "text": "body", "html": "<p>body</p>",
 *     "accountId": "iecc" }
 */

import * as fs from "node:fs";
import { initMailSend, queueMessage, type MailSendConfig, type MailMessage } from "./index.js";

const args = process.argv.slice(2);

function getArg(name: string): string | undefined {
    const shorts: Record<string, string> = { q: "queue" };
    const longIdx = args.indexOf(`--${name}`);
    const shortKey = Object.entries(shorts).find(([, v]) => v === name)?.[0];
    const shortIdx = shortKey ? args.indexOf(`-${shortKey}`) : -1;
    const i = Math.max(longIdx, shortIdx);
    if (i === -1 || i + 1 >= args.length) return undefined;
    return args[i + 1];
}

function hasFlag(name: string): boolean {
    return args.includes(`--${name}`);
}

// Load config
const configPath = getArg("config") || "mailsend.json";
if (!fs.existsSync(configPath)) {
    console.error(`Config file not found: ${configPath}`);
    console.error(`Create a mailsend.json with baseDir, accounts, etc.`);
    process.exit(1);
}

const config: MailSendConfig = JSON.parse(fs.readFileSync(configPath, "utf-8"));
const sender = initMailSend(config);
const accountId = getArg("queue") || config.defaultAccount || "";

// ── Queue management ──

if (hasFlag("status")) {
    const status = sender.getStatus();
    for (const [id, s] of Object.entries(status)) {
        console.log(`  ${id}: ${s.pending} pending, ${s.failed} failed`);
    }
    process.exit(0);
}

if (hasFlag("process") && !hasFlag("new")) {
    if (accountId && accountId !== config.defaultAccount) {
        await sender.processQueue(accountId);
    } else {
        await sender.processAllQueues();
    }
    process.exit(0);
}

// ── Create new message ──

if (hasFlag("new")) {
    let msg: Partial<MailMessage> = {};

    const jsonArg = getArg("json");
    if (jsonArg) {
        // Load from JSON file or stdin
        const raw = jsonArg === "-"
            ? fs.readFileSync(0, "utf-8")  // stdin
            : fs.readFileSync(jsonArg, "utf-8");
        msg = JSON.parse(raw);
    } else {
        // Build from CLI args
        const to = getArg("to");
        if (!to) {
            console.error("--new requires --to or --json");
            process.exit(1);
        }
        msg = {
            to: to.split(",").map(s => s.trim()),
            subject: getArg("subject") || "(no subject)",
            text: getArg("body") || "",
            html: getArg("html"),
        };
    }

    // Set from/account
    const acctId = msg.accountId || accountId;
    const acct = config.accounts[acctId];
    if (!acct) {
        console.error(`Unknown account: ${acctId}`);
        console.error(`Available: ${Object.keys(config.accounts).join(", ")}`);
        process.exit(1);
    }

    msg.from = msg.from || getArg("from") || acct.from || acct.user;
    msg.accountId = acctId;

    if (!msg.to?.length) {
        console.error("Message must have at least one recipient (to)");
        process.exit(1);
    }

    const filename = queueMessage(msg as MailMessage);
    console.log(`Queued: ${filename}`);
    setTimeout(() => process.exit(0), 2000);
} else if (!hasFlag("status") && !hasFlag("process")) {
    console.error("Usage:");
    console.error("  mailx-send --new --to addr --subject text [--body text] [-q account]");
    console.error("  mailx-send --new --json message.json [-q account]");
    console.error("  mailx-send --process [-q account]");
    console.error("  mailx-send --status");
    process.exit(1);
}
