# Copyright 2026 Espressif Systems (Shanghai) Co., Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import queue
import threading
import time
from typing import List

import serial
import serial.tools.list_ports


class SerialDriver:
    """
    Real Serial Port Driver.
    Wraps pyserial to provide the same interface as MockDevice.
    """

    def __init__(self, port, baudrate=115200, timeout=0.1):
        self.port = port
        self.baudrate = baudrate
        self.timeout = timeout
        self.serial = None
        self.is_open = False

    def open(self):
        if self.is_open:
            return
        try:
            self.serial = serial.Serial(self.port, self.baudrate, timeout=self.timeout)
            self.is_open = True
        except serial.SerialException as e:
            raise Exception(f"Failed to open {self.port}: {e}")

    def close(self):
        self.is_open = False
        if self.serial:
            self.serial.close()
            self.serial = None

    def write(self, data: str):
        if not self.is_open or not self.serial:
            raise Exception("Port not open")
        try:
            self.serial.write(data.encode("utf-8"))
        except serial.SerialException as e:
            self.close()
            raise e

    def write_raw(self, data: bytes):
        if not self.is_open or not self.serial:
            raise Exception("Port not open")
        try:
            self.serial.write(data)
        except serial.SerialException as e:
            self.close()
            raise e

    def readline(self) -> str:
        if not self.is_open or not self.serial:
            return None
        try:
            # readline returns bytes, decode to str
            line = self.serial.readline()
            if line:
                try:
                    return line.decode("utf-8", errors="ignore")
                except:
                    return None
            return None
        except serial.SerialException:
            self.close()
            return None

    @staticmethod
    def list_ports() -> List[str]:
        ports = serial.tools.list_ports.comports()
        return [p.device for p in ports]
