import os
from openai import OpenAI
from httpx import Client as HTTPXClient, Timeout


def summarize_sign_codes(municipality, zoning, muni_data, geo):
    """
    Generates a clean, human-readable sign code summary using OpenAI's GPT model.
    Fully bypasses proxy settings and gracefully handles API errors.
    """
    api_key = os.getenv("OPENAI_API_KEY")
    if not api_key:
        return "AI summary unavailable (missing OPENAI_API_KEY)."

    try:
        # 🔒 Create a clean HTTP transport — no proxies, no inherited env vars
        clean_httpx = HTTPXClient(
            proxies=None,
            timeout=Timeout(40.0),
            trust_env=False,
        )

        # ✅ Create the OpenAI client using the clean HTTP session
        client = OpenAI(api_key=api_key, http_client=clean_httpx)

        # 🧠 System behavior: concise, practical, not markdown-heavy
        system_msg = (
            "You are Sign Code Scout, an expert assistant for sign companies. "
            "Summarize municipal sign code rules in a professional, easy-to-read format. "
            "Avoid markdown symbols or bullet characters. "
            "Write short paragraphs with clear headings using plain text only. "
            "If specific values are missing, state 'Information not available'. "
            "Finish with 2–3 realistic, practical steps for verifying or obtaining official data."
        )

        # 🏙️ User context
        user_msg = f"""
Municipality: {municipality}
Coordinates: lat={geo.get('lat')}, lon={geo.get('lon')}
Zoning: {zoning or 'Unknown'}

Source Data (unverified or partial):
{muni_data or 'No structured data available.'}

Task:
Provide a structured summary of sign regulations organized by sign type.
Include maximum size/height, setbacks, illumination, and permit requirements if available.
End with clear recommendations on how to confirm official details.
Avoid markdown and keep tone clear and factual.
"""

        # 💬 Run the completion
        response = client.chat.completions.create(
            model="gpt-4o-mini",
            messages=[
                {"role": "system", "content": system_msg},
                {"role": "user", "content": user_msg},
            ],
            temperature=0.25,
            max_tokens=700,
        )

        ai_text = response.choices[0].message.content.strip()

        # 🏁 Append a signature/footer for credibility
        return f"{ai_text}\n\n— Generated by Sign Code Scout AI"

    except Exception as e:
        # ✅ Prevent crashes if API or network fails
        return f"AI summary unavailable (error: {e})"
