"""
BizNode Support — Ollama AI Analyzer
=====================================
Uses Ollama (qwen3.5:4b) to analyze support emails and log files.
"""

import logging
import os
import requests

log = logging.getLogger("biznode.support.analyzer")

OLLAMA_URL = "http://localhost:11434/api/generate"
MODEL = "qwen3.5:4b"

# LLM Gateway (nodemonitor) — primary LLM source, local Ollama as fallback
LLM_GATEWAY_URL = os.getenv("LLM_GATEWAY_URL", "http://1bz.biz:7333/llm/generate")
LLM_GATEWAY_KEY = os.getenv("LLM_GATEWAY_KEY", "Nk2xGrJ4ZyERwBa3mCH33iF_CwgWh6uRMFjKvcc8e48")
LLM_GATEWAY_MODEL = os.getenv("LLM_GATEWAY_MODEL", "qwen3:14b")
USE_LLM_GATEWAY = os.getenv("USE_LLM_GATEWAY", "true").lower() == "true"


def _call_llm_gateway(prompt: str, system: str = "", model: str | None = None) -> str | None:
    """Call the nodemonitor LLM gateway. Returns response text or None on failure."""
    if not USE_LLM_GATEWAY:
        return None
    try:
        resp = requests.post(
            LLM_GATEWAY_URL,
            json={
                "prompt": prompt,
                "system": system,
                "model": model or LLM_GATEWAY_MODEL,
                "caller_node": "biznode-support",
            },
            headers={"x-api-key": LLM_GATEWAY_KEY},
            timeout=120,
        )
        resp.raise_for_status()
        text = resp.json().get("response", "").strip()
        if text:
            return text
        return None
    except Exception as exc:
        log.warning("LLM gateway failed, falling back to local Ollama: %s", exc)
        return None

SYSTEM_PROMPT = (
    "You are BizNode technical support. Analyze the customer's issue and provide "
    "clear, step-by-step solutions. Be professional and helpful.\n\n"
    "IMPORTANT: Do NOT invent or guess system metrics (disk usage, memory, DB size, "
    "utilization percentages). Only reference data if the customer provided it in their "
    "message or logs. Never hallucinate numbers.\n\n"
    "Common issues:\n"
    "- Docker not installed or not running\n"
    "- Ollama not running or model not pulled\n"
    "- PostgreSQL connection failed (wrong credentials, service not started)\n"
    "- Port conflicts (7777, 6333, 11434)\n"
    "- Python version too old (needs 3.10+)\n"
    "- Missing pip packages (requirements.txt not installed)\n"
    "- License activation failures\n"
    "- Qdrant container not starting\n"
    "- SMTP not configured (OTP email fails during onboarding)\n"
    "- Bot not responding (check bot_runner.py and dashboard connectivity)\n\n"
    "Always suggest checking the BizNode dashboard at http://localhost:7777 "
    "and running 'python service_manager.py restart' after fixes.\n"
    "Keep responses concise and actionable. Use numbered steps. "
    "Only state facts you can verify from the customer's message."
)

_FALLBACK_RESPONSE = (
    "Thank you for contacting BizNode Support.\n\n"
    "We were unable to run an automated analysis at this time. "
    "Please try the following general troubleshooting steps:\n\n"
    "1. Make sure Docker Desktop is running\n"
    "2. Verify Ollama is installed and running: ollama list\n"
    "3. Check your .env configuration file\n"
    "4. Run: pip install -r requirements.txt\n"
    "5. Restart BizNode: python service_manager.py restart\n\n"
    "If the problem persists, please reply with the full error message "
    "or press the Support button in your BizNode dashboard to send logs."
)


def _call_ollama(prompt: str, system: str = SYSTEM_PROMPT) -> str:
    # Try LLM gateway first (better model, centralized)
    gateway_result = _call_llm_gateway(prompt, system)
    if gateway_result:
        return gateway_result

    # Fallback to local Ollama
    try:
        resp = requests.post(
            OLLAMA_URL,
            json={
                "model": MODEL,
                "prompt": prompt,
                "system": system,
                "stream": False,
                "temperature": 0.4,
            },
            timeout=120,
        )
        resp.raise_for_status()
        return resp.json().get("response", "").strip()
    except requests.exceptions.ConnectionError:
        log.warning("Ollama is not reachable at %s", OLLAMA_URL)
        return ""
    except requests.exceptions.Timeout:
        log.warning("Ollama request timed out")
        return ""
    except Exception as exc:
        log.error("Ollama error: %s", exc)
        return ""


def analyze_issue(email_body: str, attachments_text: str = "") -> dict:
    combined = email_body
    if attachments_text:
        combined += "\n\n--- ATTACHED LOGS ---\n" + attachments_text[:8000]

    prompt = (
        f"A customer sent this support email. Analyze the issue and provide a solution.\n\n"
        f"--- CUSTOMER MESSAGE ---\n{combined[:6000]}\n--- END ---\n\n"
        f"Provide:\n1. Issue summary (one line)\n2. Root cause\n3. Step-by-step fix\n4. Prevention tip"
    )

    result = _call_ollama(prompt)
    if not result:
        return {
            "summary": "Unable to analyze automatically",
            "response": _FALLBACK_RESPONSE,
            "has_ai": False,
        }

    return {
        "summary": result.split("\n")[0] if result else "",
        "response": result,
        "has_ai": True,
    }


def analyze_log_file(log_content: str) -> dict:
    prompt = (
        f"Analyze these BizNode installation/runtime logs. "
        f"Find errors, warnings, and issues. Suggest fixes.\n\n"
        f"--- LOGS ---\n{log_content[:8000]}\n--- END ---\n\n"
        f"Provide:\n1. Issues found\n2. Most likely root cause\n3. Step-by-step fix"
    )

    result = _call_ollama(prompt)
    if not result:
        return {
            "issues": ["Could not analyze logs automatically"],
            "response": _FALLBACK_RESPONSE,
            "has_ai": False,
        }

    return {
        "issues": [line.strip() for line in result.split("\n") if line.strip()],
        "response": result,
        "has_ai": True,
    }


def generate_response(ticket_history: str, latest_message: str) -> str:
    prompt = (
        f"Here is the support ticket conversation so far:\n\n"
        f"--- HISTORY ---\n{ticket_history[:4000]}\n--- END HISTORY ---\n\n"
        f"The customer just sent this new message:\n\n"
        f"--- NEW MESSAGE ---\n{latest_message[:4000]}\n--- END ---\n\n"
        f"Write a helpful, professional support response. "
        f"Address their specific concern and provide clear next steps."
    )

    result = _call_ollama(prompt)
    if not result:
        return _FALLBACK_RESPONSE

    return result
