#pragma once
// chassis_driver_adapter.hpp
// 真实底盘驱动适配器边界。
// Windows 车端 agent 的 TCP 协议层只依赖这个接口，不直接调用厂商 SDK、CAN 或 PLC。

#include <chrono>
#include <string>

#include "data_types.hpp"

namespace vaw
{

inline int64_t unix_time_us()
{
    return std::chrono::duration_cast<std::chrono::microseconds>(
        std::chrono::system_clock::now().time_since_epoch()).count();
}

inline std::string request_job_id(const MotionPrimitiveRequest& req)
{
    if (!req.header.request_id.empty())
        return req.header.request_id;
    if (!req.test_case_id.empty())
        return req.test_case_id;
    return "unknown_chassis_job";
}

class ChassisDriverAdapter
{
public:
    virtual ~ChassisDriverAdapter() = default;

    // 查询真实底盘是否具备执行标定动作的条件。
    virtual ChassisReadinessResponse get_readiness(const nlohmann::json& req) = 0;

    // 执行动作原语。该调用应阻塞到动作完成、失败或超时，然后返回完整结果。
    virtual ChassisJobResult execute_motion_primitive(const MotionPrimitiveRequest& req) = 0;

    // 执行紧急制动。无论当前任务状态如何，真实实现都应优先停车。
    virtual StandardResponse emergency_brake(const nlohmann::json& req) = 0;
};

class SafeStubChassisDriverAdapter final : public ChassisDriverAdapter
{
public:
    ChassisReadinessResponse get_readiness(const nlohmann::json& req) override
    {
        (void)req;
        ChassisReadinessResponse rsp;
        rsp.success               = false;
        rsp.error_code            = ErrorCode::NOT_READY;
        rsp.message               = "未接入真实底盘驱动，禁止执行底盘动作。";
        rsp.agent_ready           = true;
        rsp.chassis_driver_online = false;
        rsp.motion_control_ready  = false;
        rsp.estop_released        = false;
        rsp.vehicle_safe_to_move  = false;
        rsp.telemetry_available   = false;
        rsp.checked_timestamp_us  = unix_time_us();
        return rsp;
    }

    ChassisJobResult execute_motion_primitive(const MotionPrimitiveRequest& req) override
    {
        ChassisJobResult result;
        result.success              = false;
        result.error_code           = ErrorCode::NOT_READY;
        result.message              = "未接入真实底盘驱动，动作原语已拒绝。";
        result.job_id               = request_job_id(req);
        result.data_quality_passed  = false;
        result.suitable_for_commit  = false;
        result.validation_summary.auto_acceptance_passed = false;
        return result;
    }

    StandardResponse emergency_brake(const nlohmann::json& req) override
    {
        (void)req;
        StandardResponse rsp;
        rsp.success = false;
        rsp.error_code = ErrorCode::NOT_READY;
        rsp.message = "未接入真实底盘驱动，无法确认紧急制动是否已执行。";
        return rsp;
    }
};

}  // namespace vaw
