#!/usr/bin/env python3
"""
Dynamic MUE (Medically Unlikely Edits) Checker

Queries the _ncci_ database for MUE limits instead of hardcoding.
NO hardcoded limits - all data from database.

Version: 1.0
Date: November 2, 2025
"""

import pyodbc
from typing import Dict, List, Tuple

class DynamicMUEChecker:
    """
    Checks for MUE violations by querying _ncci_.mue.mue_practitioner database
    """
    
    def __init__(self):
        """Initialize connection to _ncci_ database"""
        self.conn_str = (
            "DRIVER={ODBC Driver 17 for SQL Server};"
            "SERVER=127.0.0.1,1433;"
            "DATABASE=_ncci_;"
            "UID=SA;"
            "PWD=Bbanwo@1980!"
        )
        self.conn = None
        self.mue_cache = {}  # Cache MUE limits to avoid repeated queries
        self._connect()
    
    def _connect(self):
        """Establish database connection"""
        try:
            self.conn = pyodbc.connect(self.conn_str, timeout=3)
        except Exception as e:
            print(f"[MUE Checker] Warning: Could not connect to _ncci_: {e}")
            self.conn = None
    
    def get_mue_limit(self, code: str) -> Tuple[int, str]:
        """
        Get MUE limit for a code from database
        
        Args:
            code: CPT/HCPCS code
            
        Returns:
            (mue_limit, rationale)
        """
        if not self.conn:
            return (None, "Database unavailable")
        
        # Check cache first
        if code in self.mue_cache:
            return self.mue_cache[code]
        
        cursor = self.conn.cursor()
        
        try:
            cursor.execute("""
                SELECT practitioner_mue_values, mue_rationale
                FROM [mue].[mue_practitioner]
                WHERE hcpcs_cpt_code = ?
            """, (code,))
            
            result = cursor.fetchone()
            
            if result:
                mue_limit = result[0]
                rationale = result[1] or "No rationale"
                
                # Cache it
                self.mue_cache[code] = (mue_limit, rationale)
                
                return (mue_limit, rationale)
            else:
                # Code not in database - no MUE limit
                self.mue_cache[code] = (None, "Code not in MUE database")
                return (None, "Code not in MUE database")
        
        except Exception as e:
            print(f"[MUE Checker] Error querying code {code}: {e}")
            return (None, f"Query error: {e}")
    
    def check_mue_violations(
        self, 
        procedure_codes: Dict[str, str],
        procedure_units: Dict[str, int]
    ) -> Tuple[bool, List[Dict]]:
        """
        Check for MUE violations
        
        Args:
            procedure_codes: Dict mapping HCPCS_CD_1 -> code
            procedure_units: Dict mapping HCPCS_CD_1 -> units
            
        Returns:
            (has_violations, violation_details)
        """
        if not self.conn:
            return (False, [])
        
        violations = []
        
        for key, code in procedure_codes.items():
            if not code:
                continue
            
            # Get units (default to 1 if not specified)
            units = procedure_units.get(key, 1)
            
            # Get MUE limit from database
            mue_limit, rationale = self.get_mue_limit(str(code))
            
            # Check for violation
            if mue_limit and units > int(mue_limit):
                violations.append({
                    'code': code,
                    'units_billed': units,
                    'mue_limit': int(mue_limit),
                    'excess_units': units - int(mue_limit),
                    'rationale': rationale,
                    'severity': 'HIGH' if units > int(mue_limit) * 2 else 'MEDIUM'
                })
        
        has_violations = len(violations) > 0
        
        return (has_violations, violations)
    
    def close(self):
        """Close database connection"""
        if self.conn:
            self.conn.close()


# Example usage
if __name__ == "__main__":
    checker = DynamicMUEChecker()
    
    # Test with fraud claim
    test_procedures = {
        'HCPCS_CD_1': '99291',
        'HCPCS_CD_2': '80053',
        'HCPCS_CD_3': '85025'
    }
    
    test_units = {
        'HCPCS_CD_1': 8,
        'HCPCS_CD_2': 15,
        'HCPCS_CD_3': 12
    }
    
    has_violations, violations = checker.check_mue_violations(test_procedures, test_units)
    
    print(f"Has MUE violations: {has_violations}")
    print(f"Violations found: {len(violations)}\n")
    
    for v in violations:
        print(f"{v['code']}: {v['units_billed']} units (limit: {v['mue_limit']})")
        print(f"  Excess: {v['excess_units']}")
        print(f"  Rationale: {v['rationale']}")
        print(f"  Severity: {v['severity']}\n")
    
    checker.close()

