from __future__ import annotations

from product_data_portable import (
    default_output_path,
    emit_error,
    emit_success,
    export_dataset_records,
    load_json_payload,
    load_records,
)


def main() -> int:
    try:
        payload = load_json_payload()
        records = load_records(payload)
        output_format = str(payload.get("output_format") or "jsonl")
        result = export_dataset_records(
            records,
            output_path=default_output_path(payload),
            output_format=output_format,
            require_validation_ok=bool(payload.get("require_validation_ok", True)),
            overwrite=bool(payload.get("overwrite", True)),
            export_table=bool(payload.get("export_table", True)),
        )
        emit_success(result)
        return 0
    except Exception as exc:  # noqa: BLE001 - CLI 需要把错误稳定转成 JSON
        emit_error(exc)
        return 1


if __name__ == "__main__":
    raise SystemExit(main())
