import grpc
from concurrent import futures
import time

import agv_calib_chassis_pb2 as chassis_pb2, agv_calib_chassis_pb2_grpc as chassis_grpc
import agv_calib_control_pb2 as control_pb2, agv_calib_control_pb2_grpc as control_grpc
import agv_calib_sensor_pb2 as sensor_pb2, agv_calib_sensor_pb2_grpc as sensor_grpc

class FakeChassis(chassis_grpc.AgvCalibChassisServiceServicer):
    def SetDiagnosticMode(self, request, context):
        mode = "纯物理直驱" if request.target_mode == 1 else "正常算法"
        print(f"\n[⚙️ 底盘硬件] 收到 Linux 夺权指令！切换至: {mode}模式")
        return chassis_pb2.StandardResponse(success=True, message="底盘已交出控制权")

class FakeControl(control_grpc.AgvCalibControlServiceServicer):
    pass # 暂未调用，保持空壳即可

class FakeSensor(sensor_grpc.SensorCalibrationServiceServicer):
    def TriggerSyncCapture(self, request, context):
        print(f"\n[📷 传感器代理] 收到冻结指令！要求拍摄: {request.sensor_ids}")
        time.sleep(0.5) 
        print("[📷 传感器代理] 咔嚓！照片和点云已锁存。取件码: 999888777")
        # 🚨 吐出取件码给行为树！
        return sensor_pb2.CaptureResponse(success=True, capture_timestamp_us=999888777)

    # 🚨 终极大招：模拟 2MB 大文件的流式分块发送！
    def DownloadImage(self, request, context):
        print(f"\n[📥 传感器代理] 收到大文件拉取请求！取件码: {request.capture_timestamp_us}, 传感器: {request.sensor_id}")
        print("[🌊 传感器代理] 正在切割 2MB 的无损 PNG 假图片，以 512KB 碎片流式发往 Linux...")
        
        chunk_size = 512 * 1024  # 每次切 512KB
        total_chunks = 4         # 发 4 次，共 2MB
        
        for i in range(total_chunks):
            is_last = (i == total_chunks - 1)
            # 伪造一点假二进制数据 (带个 PNG 文件头，否则后续 OpenCV 可能会报格式错)
            dummy_data = b'\x89PNG\r\n\x1a\n' + b'\x00' * (chunk_size - 8) if i == 0 else b'\x00' * chunk_size
            
            yield sensor_pb2.FileChunk(
                chunk_data=dummy_data,
                is_last_chunk=is_last,
                format_ext="png"
            )
            time.sleep(0.3) # 故意制造网络延迟，观察网关如何应对
            
        print("[📥 传感器代理] ✅ 2MB 碎片流全部分发完毕！")

def serve():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    chassis_grpc.add_AgvCalibChassisServiceServicer_to_server(FakeChassis(), server)
    control_grpc.add_AgvCalibControlServiceServicer_to_server(FakeControl(), server)
    sensor_grpc.add_SensorCalibrationServiceServicer_to_server(FakeSensor(), server)
    
    server.add_insecure_port('[::]:50051')
    print("🚀 [全能 Windows 假车端] 已启动，监听 50051 端口，等待 ROS 2 召唤...")
    server.start()
    server.wait_for_termination()

if __name__ == '__main__':
    serve()