# -*- coding: utf-8 -*-
"""
HIPPO Service - AI Chat and Symptom Analysis
"""

import os
from typing import Optional, List, Dict, Any
from groq import Groq
from .config import (
    HIPPO_CONFIG,
    APP_PAGES,
    SYMPTOMS,
    DISEASES,
    DOCTOR_TYPES,
    get_system_prompt
)


class HippoService:
    def __init__(self):
        api_key = os.getenv('GROQ_API_KEY')
        self.client = Groq(api_key=api_key) if api_key else None
        self.conversation_history: List[Dict[str, str]] = []

    def chat(self, message: str, history: Optional[List[Dict]] = None) -> Dict[str, Any]:
        if history:
            self.conversation_history = history[-6:]

        intent = self._detect_intent(message)

        if intent == 'symptoms':
            symptom_result = self._analyze_symptoms(message)
            if symptom_result['diseases']:
                return {
                    'message': self._format_symptom_response(symptom_result),
                    'intent': 'symptoms',
                    'quickReplies': ['I have another symptom', 'Thank you'],
                    'analysis': symptom_result
                }

        if intent == 'navigation':
            nav_response = self._get_navigation_help(message)
            if nav_response:
                return {
                    'message': nav_response,
                    'intent': 'navigation',
                    'quickReplies': ['Another page', 'Symptom guidance']
                }

        if self.client:
            try:
                response = self._get_ai_response(message)
                return {
                    'message': response,
                    'intent': intent,
                    'quickReplies': self._get_quick_replies(intent)
                }
            except Exception as e:
                print(f"HIPPO AI Error: {e}")

        return {
            'message': self._get_fallback_response(intent),
            'intent': intent,
            'quickReplies': self._get_quick_replies(intent)
        }

    def _detect_intent(self, message: str) -> str:
        lower = message.lower()

        symptom_keywords = [
            'ağrı', 'acı', 'ateş', 'bulantı', 'baş', 'karın', 'göğüs',
            'nefes', 'öksürük', 'halsiz', 'yorgun', 'şiş', 'kaşıntı',
            'neyim var', 'ne var', 'hasta', 'rahatsız', 'belirti', 'semptom',
            'doktor', 'hangi doktor', 'agri', 'ates', 'bulanti',
            'pain', 'ache', 'fever', 'nausea', 'headache', 'dizzy', 'dizziness',
            'cough', 'fatigue', 'tired', 'swelling', 'itch', 'rash', 'symptom',
            'sick', 'doctor', 'which doctor', 'what do i have', 'shortness of breath'
        ]

        nav_keywords = [
            'sayfa', 'nereden', 'nasıl', 'nerede', 'bul', 'git',
            'dashboard', 'tahlil', 'reçete', 'muayene', 'rapor',
            'grafik', 'timeline', 'görüntü', 'cihaz', 'hastalık',
            'hipograf', 'uygulama', 'menü', 'nasil',
            'page', 'where', 'how', 'find', 'go', 'lab', 'test', 'prescription',
            'visit', 'diagnosis', 'diagnoses', 'plot', 'calendar', 'scheduler',
            'imaging', 'image', 'vaccination', 'wearable', 'device', 'settings',
            'practitioner', 'patient', 'app', 'menu'
        ]

        if any(kw in lower for kw in symptom_keywords):
            return 'symptoms'

        if any(kw in lower for kw in nav_keywords):
            return 'navigation'

        if any(kw in lower for kw in ['merhaba', 'selam', 'hey', 'hello', 'hi', 'sa']):
            return 'greeting'

        return 'general'

    def _analyze_symptoms(self, message: str) -> Dict[str, Any]:
        lower = message.lower()

        symptom_keywords = {
            'baş ağr': 'headache', 'bas agr': 'headache', 'başım ağ': 'headache',
            'headache': 'headache', 'head pain': 'headache',
            'baş dön': 'dizziness', 'bas don': 'dizziness',
            'dizzy': 'dizziness', 'dizziness': 'dizziness',
            'ateş': 'fever', 'ates': 'fever',
            'fever': 'fever',
            'yorgun': 'fatigue', 'halsiz': 'fatigue',
            'fatigue': 'fatigue', 'tired': 'fatigue',
            'öksür': 'cough', 'oksur': 'cough',
            'cough': 'cough',
            'boğaz': 'sore_throat', 'bogaz': 'sore_throat',
            'sore throat': 'sore_throat',
            'burun ak': 'runny_nose',
            'runny nose': 'runny_nose',
            'göğüs ağr': 'chest_pain', 'gogus agr': 'chest_pain',
            'chest pain': 'chest_pain',
            'nefes': 'shortness_breath',
            'shortness of breath': 'shortness_breath', 'breathless': 'shortness_breath',
            'karın ağr': 'stomach_pain', 'karin agr': 'stomach_pain',
            'stomach pain': 'stomach_pain', 'abdominal pain': 'stomach_pain',
            'mide bulan': 'nausea', 'bulantı': 'nausea', 'bulanti': 'nausea',
            'nausea': 'nausea', 'nauseous': 'nausea',
            'sırt ağr': 'back_pain', 'sirt agr': 'back_pain', 'bel ağr': 'back_pain',
            'back pain': 'back_pain',
            'eklem ağr': 'joint_pain',
            'joint pain': 'joint_pain',
            'döküntü': 'rash', 'dokuntu': 'rash',
            'rash': 'rash',
            'kaşın': 'rash', 'kasin': 'rash',
            'itch': 'rash',
            'kaygı': 'anxiety', 'kaygi': 'anxiety',
            'anxiety': 'anxiety', 'anxious': 'anxiety',
            'uyku': 'insomnia', 'uykusuz': 'insomnia',
            'insomnia': 'insomnia', 'cannot sleep': 'insomnia'
        }

        matched_symptom_ids = set()
        for keyword, symptom_id in symptom_keywords.items():
            if keyword in lower:
                matched_symptom_ids.add(symptom_id)

        for symptom in SYMPTOMS:
            if symptom['name_tr'].lower() in lower:
                matched_symptom_ids.add(symptom['id'])

        if not matched_symptom_ids:
            return {'symptoms': [], 'diseases': [], 'doctor': None}

        matched_symptoms = [s for s in SYMPTOMS if s['id'] in matched_symptom_ids]

        matched_diseases = []
        for disease in DISEASES:
            match_count = len(set(disease['symptoms']) & matched_symptom_ids)
            if match_count >= 1:
                match_score = match_count / len(disease['symptoms'])
                matched_diseases.append({
                    'disease': disease,
                    'match_count': match_count,
                    'match_score': match_score
                })

        matched_diseases.sort(key=lambda x: x['match_score'], reverse=True)
        top_diseases = [d['disease'] for d in matched_diseases[:3]]

        recommended_doctor = None
        if top_diseases:
            for d in top_diseases:
                if d['urgency'] == 'urgent':
                    recommended_doctor = DOCTOR_TYPES.get('emergency')
                    break
            if not recommended_doctor:
                doctor_type = top_diseases[0]['doctor_type']
                recommended_doctor = DOCTOR_TYPES.get(doctor_type)

        return {
            'symptoms': matched_symptoms,
            'diseases': top_diseases,
            'doctor': recommended_doctor
        }

    def _format_symptom_response(self, analysis: Dict[str, Any]) -> str:
        symptoms = analysis['symptoms']
        diseases = analysis['diseases']
        doctor = analysis['doctor']

        lines = []

        symptom_names = [s['name_tr'] for s in symptoms]
        lines.append(f"Detected symptoms: {', '.join(symptom_names)}")
        lines.append("")

        if diseases:
            lines.append("Possible conditions:")
            for disease in diseases:
                urgency_text = ""
                if disease['urgency'] == 'urgent':
                    urgency_text = " (urgent)"
                elif disease['urgency'] == 'soon':
                    urgency_text = " (seek care soon)"
                lines.append(f"  - {disease['name_tr']}{urgency_text}")
            lines.append("")

        urgent = any(d['urgency'] == 'urgent' for d in diseases)
        if urgent:
            lines.append("WARNING: These symptoms may indicate an emergency.")
            lines.append("Please seek emergency care immediately or call your local emergency number.")
        elif doctor:
            lines.append(f"Suggested clinician: {doctor['name']}")
            lines.append(f"({doctor['description']})")

        lines.append("")
        lines.append("Note: This is informational guidance only and cannot replace a doctor or licensed clinician.")

        return "\n".join(lines)

    def _get_navigation_help(self, message: str) -> Optional[str]:
        lower = message.lower()

        for key, page in APP_PAGES.items():
            page_keywords = [page['name'].lower(), key, page['path'].strip('/')]

            if any(kw in lower for kw in page_keywords if kw):
                features = '\n  - '.join(page['features'][:3])
                return f"""{page['name']}

{page['description']}

Features:
  - {features}

Access: Use the left sidebar or go to {page['path']}."""

        if 'hipograf' in lower or 'uygulama' in lower or 'ne yapabilirim' in lower or 'app' in lower or 'what can i do' in lower:
            pages_list = '\n'.join([f"  - {p['name']} ({p['path']})" for p in APP_PAGES.values()])
            return f"""Welcome to Hipograf!

Hipograf helps patients and practitioners visualize, review, and manage health data.

Available pages:
{pages_list}

You can reach them from the left sidebar."""

        return None

    def _get_ai_response(self, message: str) -> str:
        messages = [
            {"role": "system", "content": get_system_prompt()},
            *self.conversation_history,
            {"role": "user", "content": message}
        ]

        completion = self.client.chat.completions.create(
            model=HIPPO_CONFIG['model'],
            messages=messages,
            max_tokens=HIPPO_CONFIG['max_tokens'],
            temperature=HIPPO_CONFIG['temperature']
        )

        response = completion.choices[0].message.content

        self.conversation_history.append({"role": "user", "content": message})
        self.conversation_history.append({"role": "assistant", "content": response})

        if len(self.conversation_history) > 6:
            self.conversation_history = self.conversation_history[-6:]

        return response

    def _get_fallback_response(self, intent: str) -> str:
        if intent == 'greeting':
            return HIPPO_CONFIG['greeting']

        if intent == 'symptoms':
            return """Could you describe your symptoms in a little more detail?

For example:
- "I have a headache and fever"
- "I feel stomach pain and nausea"
- "I have been coughing for a few days"

Share your symptoms, and I can give general guidance about possible directions and what type of clinician may be appropriate. This does not replace medical care."""

        if intent == 'navigation':
            return """Hipograf includes these pages:

- Dashboard (/) - 3D body model, timeline/agenda/calendar, and widgets
- Timeline (/timeline) - Events across timeline, agenda, calendar, and history views
- Plots (/plots) - Lab, prescription, and wearable data plotted over time
- Hospital Visits (/visits) - Visit history, diagnoses, notes, and linked prescriptions
- Prescriptions (/prescriptions) - Medication details, safety, side effects, and CSV export
- Diagnoses (/diagnoses) - Diagnosis history, ICD codes, severity, details, and CSV export
- Lab Tests (/tests) - Lab results, reference ranges, PDF scanning, and plotting links
- Imaging (/images) - Radiology images, detail view, download, and upload
- Vaccinations (/vaccinations) - Vaccine records
- Wearable Devices (/devices) - Connected device health metrics
- Settings (/settings) - Account and data management

Which page would you like help with?"""

        return """I'm HIPPO, the Hipograf health assistant.

I can help with:
- How to use Hipograf
- Page and feature guidance
- General symptom guidance

How can I help?"""

    def _get_quick_replies(self, intent: str) -> List[str]:
        if intent == 'symptoms':
            return ['I have another symptom', 'Which doctor should I see?', 'Thank you']
        if intent == 'navigation':
            return ['What is the dashboard?', 'How do I view lab tests?', 'Symptom guidance']
        if intent == 'greeting':
            return ['Introduce Hipograf', 'Symptom guidance', 'Show pages']
        return ['What is Hipograf?', 'Symptom guidance', 'Show pages']

    def get_greeting(self) -> Dict[str, Any]:
        return {
            'message': HIPPO_CONFIG['greeting'],
            'intent': 'greeting',
            'quickReplies': ['Introduce Hipograf', 'Symptom guidance', 'Show pages']
        }


_hippo_instance: Optional[HippoService] = None


def get_hippo_service() -> HippoService:
    global _hippo_instance
    if _hippo_instance is None:
        _hippo_instance = HippoService()
    return _hippo_instance
