#!/usr/bin/env node
/**
 * mailsend — create and send an email message.
 *
 * Usage:
 *   mailsend --to addr --subject "text" --body "text"
 *   mailsend -q gmail --from "Bob <bob@gmail.com>" --to addr --subject "text"
 *   mailsend --json message.json       Read message from JSON file
 *   echo '{"to":["a@b.com"],...}' | mailsend --json -    Read from stdin
 *
 * JSON 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];
}

const configPath = getArg("config") || "mailsend.json";
if (!fs.existsSync(configPath)) {
    console.error(`Config file not found: ${configPath}`);
    process.exit(1);
}

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

let msg: Partial<MailMessage> = {};

const jsonArg = getArg("json");
if (jsonArg) {
    const raw = jsonArg === "-"
        ? fs.readFileSync(0, "utf-8")
        : fs.readFileSync(jsonArg, "utf-8");
    msg = JSON.parse(raw);
} else {
    const to = getArg("to");
    if (!to) {
        console.error("Usage: mailsend --to addr --subject text [--body text] [--from addr] [-q account]");
        console.error("       mailsend --json message.json [-q account]");
        process.exit(1);
    }
    msg = {
        to: to.split(",").map(s => s.trim()),
        subject: getArg("subject") || "(no subject)",
        text: getArg("body") || "",
        html: getArg("html"),
    };
}

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);
