"""
Ultra-simple department matching using LLM
"""
import json
import logging
from typing import Dict, List
from langchain_ollama import ChatOllama

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def analyze_department(user_prompt: str, departments: List[Dict]) -> Dict:
    """
    Match user goal to department using LLM.
    Simple. Direct. No overthinking.
    """
    try:
        # Initialize LLM
        llm = ChatOllama(model="gemma3:12b", temperature=0.2)
        
        # Create department list
        dept_list = "\n".join([f"- {d['name']} (ID: {d['id']})" for d in departments])
        
        # Simple, direct prompt
        prompt = f"""Analyze this goal and match it to the most relevant department.

Goal: {user_prompt}

Available Departments:
{dept_list}

Respond in JSON format:
{{"department_name": "exact name from list", "department_id": number, "confidence": "high/medium/low"}}

If no good match, use: {{"department_name": "", "department_id": null, "confidence": "none"}}

Response:"""
        
        # Get LLM response
        response = llm.invoke(prompt).content.strip()
        logger.info(f"LLM response: {response}")
        
        # Parse response
        try:
            # Try to extract JSON from response
            if '{' in response and '}' in response:
                json_str = response[response.index('{'):response.rindex('}')+1]
                result = json.loads(json_str)
                
                return {
                    "identified_department": result.get("department_name", ""),
                    "department_id": result.get("department_id"),
                    "confidence": result.get("confidence", "low")
                }
        except (json.JSONDecodeError, ValueError) as e:
            logger.warning(f"JSON parse failed, trying text match: {e}")
            
            # Fallback: Simple text matching
            response_lower = response.lower()
            for dept in departments:
                if dept['name'].lower() in response_lower:
                    return {
                        "identified_department": dept['name'],
                        "department_id": dept['id'],
                        "confidence": "medium"
                    }
        
        # No match found
        return {
            "identified_department": "",
            "department_id": None,
            "confidence": "none"
        }
        
    except Exception as e:
        logger.error(f"Analysis failed: {e}")
        return {
            "identified_department": "",
            "department_id": None,
            "confidence": "none",
            "error": str(e)
        }

# That's it. That's the whole file.

if __name__ == "__main__":
    # Test it
    test_departments = [
        {"id": 1, "name": "Human Resources"},
        {"id": 2, "name": "Information Technology"},
        {"id": 3, "name": "Sales"},
        {"id": 4, "name": "Marketing"}
    ]
    
    result = analyze_department(
        "I want to improve team communication and collaboration",
        test_departments
    )
    
    print(json.dumps(result, indent=2))