import pandas as pd
import json

# Import your matching engine (adjust the import based on your actual code)
# from src.engine import YourMatchingEngine

class TestMatchingAccuracy:
    """Test suite for B2B matching accuracy"""
    
    def __init__(self, config_path='config/test_data_paths.json'):
        with open(config_path, 'r') as f:
            self.config = json.load(f)
    
    def load_test_data(self, size='small'):
        """Load test datasets"""
        dataset = self.config['test_datasets'][size]
        print(f"\nLoading {size} dataset: {dataset['description']}")
        
        crm_df = pd.read_csv(dataset['crm_data'])
        foreign_df = pd.read_csv(dataset['foreign_data'])
        
        print(f"  CRM records: {len(crm_df):,}")
        print(f"  Foreign records: {len(foreign_df):,}")
        
        return crm_df, foreign_df
    
    def run_baseline_test(self, crm_df, foreign_df):
        """Run baseline exact matching test"""
        print("\n=== BASELINE TEST: Exact Domain Matching ===")
        
        # Simple exact domain matching
        crm_domains = crm_df[crm_df['Domain (website)'].notna()]['Domain (website)'].str.lower()
        foreign_domains = foreign_df[foreign_df['Domain'].notna()]['Domain'].str.lower()
        
        exact_matches = set(crm_domains) & set(foreign_domains)
        
        print(f"Exact domain matches: {len(exact_matches):,}")
        print(f"Match rate: {len(exact_matches)/len(foreign_domains)*100:.1f}%")
        
        return exact_matches
    
    def analyze_unmatched(self, crm_df, foreign_df, exact_matches):
        """Analyze why records didn't match"""
        print("\n=== UNMATCHED ANALYSIS ===")
        
        # Find records with no domain
        crm_no_domain = crm_df[crm_df['Domain (website)'].isna()]
        foreign_no_domain = foreign_df[foreign_df['Domain'].isna()]
        
        print(f"CRM records without domain: {len(crm_no_domain):,}")
        print(f"Foreign records without domain: {len(foreign_no_domain):,}")
        
        # Sample some unmatched records
        print("\nSample unmatched records (no domain):")
        for _, row in foreign_no_domain.head(5).iterrows():
            print(f"  - {row['Company / Account']}")
    
    def test_your_matcher(self, crm_df, foreign_df):
        """Test your actual matching engine"""
        print("\n=== TESTING YOUR MATCHER ===")
        
        # TODO: Replace with your actual matcher
        # Example structure:
        '''
        from your_matcher import FuzzyMatcher
        
        matcher = FuzzyMatcher()
        start_time = time.time()
        
        matches = matcher.match(crm_df, foreign_df)
        
        elapsed = time.time() - start_time
        
        print(f"Your matcher found: {len(matches):,} matches")
        print(f"Time taken: {elapsed:.2f} seconds")
        print(f"Match rate: {len(matches)/len(foreign_df)*100:.1f}%")
        '''
        
        print("TODO: Import and test your actual matcher here")
    
    def run_all_tests(self):
        """Run complete test suite"""
        print("="*60)
        print("B2B MATCHING TEST SUITE")
        print("="*60)
        
        # Test different dataset sizes
        for size in ['small', 'medium', 'large']:
            crm_df, foreign_df = self.load_test_data(size)
            
            # Run baseline test
            exact_matches = self.run_baseline_test(crm_df, foreign_df)
            
            # Analyze unmatched
            self.analyze_unmatched(crm_df, foreign_df, exact_matches)
            
            # Test your matcher
            self.test_your_matcher(crm_df, foreign_df)
            
            print("\n" + "-"*60)

if __name__ == "__main__":
    tester = TestMatchingAccuracy()
    tester.run_all_tests()
