/**
 * 独立子进程入口：供 Next API 通过 spawn 调用，避免 webpack 打包 Playwright。
 */
import { loadDevEnv } from "@/lib/dev-env";
import type {
  AddressLookupInput,
  MothershipCandidatesResult,
} from "@/modules/address/types";
import { RpaError } from "@/modules/rpa/errors";
import { fetchMothershipAddressCandidates } from "@/workers/rpa/address-candidates";

loadDevEnv({ quiet: true });

type CliInput = {
  pickup: AddressLookupInput;
  delivery: AddressLookupInput;
};

async function readStdinJson(): Promise<CliInput> {
  const chunks: Buffer[] = [];
  for await (const chunk of process.stdin) {
    chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
  }
  return JSON.parse(Buffer.concat(chunks).toString("utf8")) as CliInput;
}

function writeResult(payload: unknown, exitCode: number): void {
  process.stdout.write(`${JSON.stringify(payload)}\n`);
  process.exit(exitCode);
}

async function main(): Promise<void> {
  const input = await readStdinJson();
  try {
    const data: MothershipCandidatesResult =
      await fetchMothershipAddressCandidates(input);
    writeResult({ ok: true, data }, 0);
  } catch (error) {
    if (error instanceof RpaError) {
      writeResult(
        {
          ok: false,
          code: error.code,
          message: error.message,
          retryable: error.retryable,
        },
        1,
      );
      return;
    }
    writeResult(
      {
        ok: false,
        code: "INTERNAL_ERROR",
        message: error instanceof Error ? error.message : String(error),
        retryable: false,
      },
      1,
    );
  }
}

main().catch((error) => {
  writeResult(
    {
      ok: false,
      code: "INTERNAL_ERROR",
      message: error instanceof Error ? error.message : String(error),
      retryable: false,
    },
    1,
  );
});
