import socket
import json

class CgminerAPI:
    def __init__(self, host='127.0.0.1', port=4028):
        self.host = host
        self.port = port

    def _send_command(self, command, parameter=None):
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.settimeout(2)
            s.connect((self.host, self.port))
            
            payload = {"command": command}
            if parameter:
                payload["parameter"] = parameter
                
            s.send(json.dumps(payload).encode('utf-8'))
            
            response = ""
            while True:
                data = s.recv(4096)
                if not data:
                    break
                response += data.decode('utf-8').replace('\x00', '')
                
            s.close()
            
            if response:
                return json.loads(response)
            return None
        except Exception as e:
            print(f"Error communicating with cgminer: {e}")
            return None

    def summary(self):
        """Get summary stats (hashrate, hw errors, etc)"""
        return self._send_command("summary")

    def pools(self):
        """Get pool stats"""
        return self._send_command("pools")
        
    def devs(self):
        """Get device stats (temperatures, individual chips)"""
        return self._send_command("devs")

    def stats(self):
        """Get general stats"""
        return self._send_command("stats")

    def add_pool(self, url, user, password):
        """Add a new pool"""
        # Command format for addpool might vary, usually it's command=addpool, parameter=url,user,pass
        # But cgminer api often expects just parameter string comma separated
        param = f"{url},{user},{password}"
        return self._send_command("addpool", param)
    
    def remove_pool(self, pool_id):
        return self._send_command("removepool", str(pool_id))
    
    def switch_pool(self, pool_id):
        return self._send_command("switchpool", str(pool_id))

    def restart(self):
        return self._send_command("restart")
        
    def quit(self):
        return self._send_command("quit")
