#!/usr/bin/env python3
"""
Простой тест для проверки автоподтверждения
Имитирует сервер Socket.IO и отправляет запрос камеры
"""
import socket
import json
import time
import threading
from http.server import HTTPServer, BaseHTTPRequestHandler

class TestServer:
    def __init__(self, host='192.168.219.108', port=3002):
        self.host = host
        self.port = port
        self.clients = []

    def start(self):
        print(f"🚀 Starting test server on {self.host}:{self.port}")
        print("📱 Configure Android app to connect to this server")
        print("🔄 Waiting for Android app connection...")

        # Простой TCP сервер для имитации Socket.IO
        server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        try:
            server_socket.bind((self.host, self.port))
            server_socket.listen(5)

            while True:
                client_socket, addr = server_socket.accept()
                print(f"📱 Android device connected from {addr}")

                # Имитируем ответ Socket.IO
                response = "HTTP/1.1 200 OK\r\n"
                response += "Content-Type: application/json\r\n"
                response += "Access-Control-Allow-Origin: *\r\n\r\n"
                response += '{"status":"connected"}'

                client_socket.send(response.encode())

                # Отправляем запрос камеры через некоторое время
                time.sleep(3)
                self.send_camera_request(client_socket)

                client_socket.close()

        except KeyboardInterrupt:
            print("\n🛑 Stopping test server")
        finally:
            server_socket.close()

    def send_camera_request(self, client_socket):
        camera_request = {
            "event": "camera-request",
            "data": {
                "sessionId": f"test_session_{int(time.time())}",
                "operatorId": "test_operator",
                "cameraType": "back",
                "timestamp": int(time.time() * 1000)
            }
        }

        print(f"📹 Sending camera request: {camera_request}")

        try:
            message = json.dumps(camera_request) + "\n"
            client_socket.send(message.encode())
            print("✅ Camera request sent to Android app")
        except Exception as e:
            print(f"❌ Failed to send camera request: {e}")

if __name__ == "__main__":
    test_server = TestServer()
    test_server.start()
