#!/usr/bin/env python3
"""
Dynamic PTP Conflict Checker

Queries the _ncci_ database instead of using hardcoded code lists.
Replaces static detection logic with dynamic lookup.

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

import pyodbc
from itertools import combinations
from typing import List, Tuple, Set

class DynamicPTPChecker:
    """
    Checks for PTP conflicts by querying _ncci_ database dynamically
    """
    
    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._connect()
    
    def _connect(self):
        """Establish database connection"""
        try:
            self.conn = pyodbc.connect(self.conn_str, timeout=3)
        except Exception as e:
            print(f"[PTP Checker] Warning: Could not connect to _ncci_: {e}")
            self.conn = None
    
    def check_ptp_conflicts(self, procedures: List[str]) -> Tuple[bool, List[Tuple], List[dict]]:
        """
        Check if any procedure pairs have PTP conflicts
        
        Args:
            procedures: List of CPT/HCPCS codes
            
        Returns:
            (has_conflicts, conflicting_pairs, conflict_details)
        """
        if not self.conn:
            # Fallback to empty if database unavailable
            return (False, [], [])
        
        if len(procedures) < 2:
            return (False, [], [])
        
        conflicting_pairs = []
        conflict_details = []
        
        cursor = self.conn.cursor()
        
        # Check all combinations of procedures
        for code1, code2 in combinations(procedures, 2):
            try:
                # Query both directions (primary/secondary can be either way)
                cursor.execute("""
                    SELECT TOP 1 
                        primary_cpt_hcpcs_code, 
                        secondary_cpt_hcpcs_code,
                        modifier,
                        ptp_edit_rationale
                    FROM vw_NCCI_PTP_Unified_Edits
                    WHERE (primary_cpt_hcpcs_code = ? AND secondary_cpt_hcpcs_code = ?)
                       OR (primary_cpt_hcpcs_code = ? AND secondary_cpt_hcpcs_code = ?)
                """, (code1, code2, code2, code1))
                
                result = cursor.fetchone()
                
                if result:
                    conflicting_pairs.append((code1, code2))
                    conflict_details.append({
                        'code1': result[0],
                        'code2': result[1],
                        'modifier_allowed': result[2],
                        'rationale': result[3],
                        'conflict_type': 'PTP_MUTUALLY_EXCLUSIVE' if result[2] == 0 else 'PTP_MODIFIER_ALLOWED'
                    })
            except Exception as e:
                # Skip on error
                pass
        
        has_conflicts = len(conflicting_pairs) > 0
        
        return (has_conflicts, conflicting_pairs, conflict_details)
    
    def get_all_conflicting_codes_for(self, code: str) -> Set[str]:
        """
        Get all codes that conflict with a given code
        
        Args:
            code: CPT/HCPCS code
            
        Returns:
            Set of conflicting codes
        """
        if not self.conn:
            return set()
        
        cursor = self.conn.cursor()
        conflicting = set()
        
        try:
            # Get all pairs where this code is involved
            cursor.execute("""
                SELECT primary_cpt_hcpcs_code, secondary_cpt_hcpcs_code
                FROM vw_NCCI_PTP_Unified_Edits
                WHERE primary_cpt_hcpcs_code = ? OR secondary_cpt_hcpcs_code = ?
            """, (code, code))
            
            for primary, secondary in cursor.fetchall():
                if primary == code:
                    conflicting.add(secondary)
                else:
                    conflicting.add(primary)
        except:
            pass
        
        return conflicting
    
    def close(self):
        """Close database connection"""
        if self.conn:
            self.conn.close()


# Example usage
if __name__ == "__main__":
    checker = DynamicPTPChecker()
    
    # Test with fraud claim codes
    test_procedures = ['33533', '33534', '93306', '93351', '99291']
    
    has_conflicts, pairs, details = checker.check_ptp_conflicts(test_procedures)
    
    print(f"Has conflicts: {has_conflicts}")
    print(f"Conflicting pairs: {pairs}")
    
    for detail in details:
        print(f"\n{detail['code1']} vs {detail['code2']}")
        print(f"  Modifier allowed: {detail['modifier_allowed']}")
        print(f"  Rationale: {detail['rationale']}")
    
    checker.close()

