import requests
import json
import logging
from typing import Optional

LOGGER = logging.getLogger(__name__)

CONTROLLER_IP = "CONTROLLER-IP-ADDRESS"  # REPLACE
CONTROLLER_PORT = 3333 
API_ENDPOINT = f"http://{CONTROLLER_IP}:{CONTROLLER_PORT}/api/service/"

def connectionRequest(ont_id: str, cvlan: str, ethernet_port: str, svlan: str, profile: str, bw: str) -> bool:
    """
    Envía una petición POST para establecer la conexión PON.
    En caso de error, muestra el comando curl equivalente.
    """
    
    payload = {
        "ont_id": ont_id,
        "cvlan": str(cvlan),
        "ethernet_port": ethernet_port,
        "svlan": str(svlan),
        "profile": profile,
        "bw": str(bw)
    }
    
    headers = {
        "accept": "application/json",
        "Content-Type": "application/json"
    }

    curl_command = _generate_curl_command(payload, headers)
    
    # --------------------DESCOMENTAR CUANDO FUNCIONE-----------------
    # try:
    #     response = requests.post(API_ENDPOINT, headers=headers, json=payload)
    #     
    #     if response.status_code == 200:
    #         LOGGER.info(f"PON Connection OK: {payload}")
    #         return True
    #         
    #     LOGGER.error(f"Connection Error. CODE: {response.status_code} - RESPONSE: {response.text}")
    #     LOGGER.info(f"CURL COMMAND: \n{curl_command}")
    #     return False
    #     
    # except requests.RequestException as e:
    #     LOGGER.error(f"Connection Error: {str(e)}")
    #     LOGGER.info(f"CURL COMMAND: \n{curl_command}")
    #     return False

    print("CURL COMMAND:")
    print(curl_command)
    return False

def _generate_curl_command(payload: dict, headers: dict) -> str:
    header_string = " ".join([f"-H '{k}: {v}'" for k, v in headers.items()])
    json_data = json.dumps(payload, indent=2).replace("'", "'\\''")
    return (
        f"curl -X POST '{API_ENDPOINT}' \\\n         {header_string} \\\n         -d $'{json_data}'"
    )
