import json
import os
import urllib.error
import urllib.request

OLLAMA_URL = os.getenv("OLLAMA_URL", "http://localhost:11434").rstrip("/")


def ask(prompt: str) -> str:
    payload = {
        "model": "deepseek-coder",
        "messages": [{"role": "user", "content": prompt}],
        "stream": False,
    }
    req = urllib.request.Request(
        f"{OLLAMA_URL}/api/chat",
        data=json.dumps(payload).encode("utf-8"),
        headers={"Content-Type": "application/json"},
        method="POST",
    )
    try:
        with urllib.request.urlopen(req, timeout=10) as resp:
            raw = resp.read().decode("utf-8")
        body = json.loads(raw)
        return body["message"]["content"]
    except urllib.error.HTTPError as exc:
        return f"ERROR: HTTP {exc.code} {exc.reason}"
    except urllib.error.URLError as exc:
        return f"ERROR: {exc.reason}"
    except json.JSONDecodeError as exc:
        return f"ERROR: Invalid JSON response: {exc}"
    except (KeyError, TypeError) as exc:
        return f"ERROR: Invalid response format: {exc}"
    except Exception as exc:
        return f"ERROR: {exc}"


if __name__ == "__main__":
    print(ask("Write docker-compose for nginx"))
