from __future__ import annotations

import json

from product_data_portable import (
    DEFAULT_REQUEST_ID,
    DEFAULT_TIMESTAMP_STEP_MS,
    emit_error,
    emit_success,
    load_json_payload,
    normalize_dataset_draft,
    resolve_portable_path,
)


def main() -> int:
    try:
        payload = load_json_payload()
        draft_text = str(payload.get("draft_text") or "")
        if not draft_text and payload.get("draft_path"):
            draft_text = resolve_portable_path(str(payload["draft_path"])).read_text(encoding="utf-8")
        source_type = str(payload.get("source_type") or "generated")
        confirmed_plan_id = str(payload.get("confirmed_plan_id") or "").strip()
        if source_type == "generated" and not confirmed_plan_id:
            raise ValueError("confirmed_plan_id is required for generated data")
        result = normalize_dataset_draft(
            draft_text,
            batch_id=str(payload.get("batch_id") or DEFAULT_REQUEST_ID),
            source_type=source_type,
            base_timestamp=payload.get("base_timestamp"),
            timestamp_step_ms=int(payload.get("timestamp_step_ms") or DEFAULT_TIMESTAMP_STEP_MS),
            default_request_id=str(payload.get("default_request_id") or DEFAULT_REQUEST_ID),
        )
        records_output_path = str(payload.get("records_output_path") or "").strip()
        return_records = bool(payload.get("return_records", not records_output_path))
        if records_output_path:
            output_path = resolve_portable_path(records_output_path)
            output_path.parent.mkdir(parents=True, exist_ok=True)
            mode = "a" if bool(payload.get("append", False)) else "w"
            with output_path.open(mode, encoding="utf-8") as fh:
                for record in result["records"]:
                    fh.write(json.dumps(record, ensure_ascii=False, separators=(",", ":")) + "\n")
            result["records_output_path"] = str(output_path)
            result["record_count"] = len(result["records"])
        if not return_records:
            result.pop("records", None)
        if confirmed_plan_id:
            result["confirmed_plan_id"] = confirmed_plan_id
        emit_success(result)
        return 0
    except Exception as exc:  # noqa: BLE001 - CLI 需要把错误稳定转成 JSON
        emit_error(exc)
        return 1


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