import os
import json
import socket
from dataclasses import dataclass
from typing import Optional
import requests


DEFAULT_API_URL = "http://localhost:8000"
DEFAULT_MODEL_DIR = os.path.join("models", "worldclass_quantum_ai")
DEFAULT_ONNX_PATH = os.path.join(DEFAULT_MODEL_DIR, "model.onnx")


@dataclass
class SDKConfig:
    api_url: str = DEFAULT_API_URL
    api_key: Optional[str] = None
    model_dir: str = DEFAULT_MODEL_DIR
    onnx_path: str = DEFAULT_ONNX_PATH
    mode: str = "auto"


def api_is_available(api_url: str = DEFAULT_API_URL, timeout: float = 0.8) -> bool:
    try:
        resp = requests.get(f"{api_url}/health", timeout=timeout)
        if resp.status_code == 200:
            return True
    except Exception:
        pass
    try:
        resp = requests.get(api_url, timeout=timeout)
        return resp.status_code == 200
    except Exception:
        return False


def read_json(path: str) -> Optional[dict]:
    try:
        with open(path, "r", encoding="utf-8") as f:
            return json.load(f)
    except Exception:
        return None


