import serial
import requests
import time

class Hardlink:
    def __init__(self, port: str, baudrate: int = 115200, api_key: str = None, model: str = "microsoft/Phi-3-mini-4k-instruct"):
        self.ser = serial.Serial(port, baudrate, timeout=1)
        self.api_key = api_key
        self.model = model
        self.base_url = "https://api-inference.huggingface.co/models/" + model

    def send_command(self, command: str):
        """Send a command to the ESP32."""
        if self.ser.is_open:
            self.ser.write((command + "\n").encode())
            time.sleep(0.1)

    def read_response(self):
        """Read response from the ESP32."""
        if self.ser.is_open:
            response = self.ser.readline().decode().strip()
            return response
        return None

    def query_huggingface(self, prompt: str):
        """Send a request to the Hugging Face model and return the response."""
        headers = {"Authorization": f"Bearer {self.api_key}"}
        payload = {"inputs": prompt}
        response = requests.post(self.base_url, headers=headers, json=payload)
        if response.status_code == 200:
            return response.json()
        else:
            return {"error": response.text}

    def control_gpio(self, pin: int, state: str):
        """Send a command to control an ESP32 GPIO pin."""
        if state.lower() in ["on", "off"]:
            command = f"GPIO {pin} {state.upper()}"
            self.send_command(command)

    def read_sensor(self, sensor_type: str):
        """Request sensor data from ESP32."""
        self.send_command(f"READ {sensor_type.upper()}")
        return self.read_response()
