import pandas as pd
import re
import unicodedata
import sys
import os
from termcolor import colored

# Define regex patterns for Company Manager related titles

company_manager_variants = [
    r"(?i)\bcompany\s?manager\b",
    r"(?i)\bmanager\s?of\s?company\b",
    r"(?i)\bcompany\s?director\b",
    r"(?i)\bcorporate\s?manager\b",
    r"(?i)\bbusiness\s?manager\b",
    r"(?i)\bexecutive\s?manager\b",
    r"(?i)\bchief\s?manager\b",
    r"(?i)\bcompany\s?maneger\b",
    r"(?i)\bcompnay\s?manager\b",
    r"(?i)\bcompanny\s?manager\b",
    r"(?i)\bcomapny\s?manager\b",
    r"(?i)\bcomany\s?manager\b",
    r"(?i)\bcompany\s?managr\b",
    r"(?i)\bcompany\s?manegar\b",
    r"(?i)\bgerente\s?de\s?empresa\b",
    r"(?i)\bgestor\s?de\s?empresa\b",
    r"(?i)\bdirector\s?de\s?empresa\b",
    r"(?i)\badministrador\s?de\s?empresa\b",
    r"(?i)\bcompany\s?lead\b",
    r"(?i)\bcompany\s?head\b",
    r"(?i)\bmanaging\s?director\b",
    r"(?i)\bexecutive\s?director\b",
    r"(?i)\bsenior\s?manager\s?of\s?company\b",
    r"(?i)\bAssistant Manager\b",
    r"(?i)\bRegional Manager\b",
    r"(?i)\bGerente\b",
    r"(?i)\bTerritory Manager\b",
    r"(?i)\bArea Manager\b",
    r"(?i)\bAssociate Director\b",
    r"(?i)\bSenior Director\b",
    r"(?i)\bExhibitor\b",
    r"(?i)\bDirector Of Operations\b",
    r"(?i)\bOperations Director\b",
    r"(?i)\bGerant\b",
    r"(?i)\bCountry\s?Manager\b",
    r"(?i)\bOperations\b",
    r"(?i)\bSenior Manager\b",
    r"(?i)\bMedtech Engineering\b",
    r"(?i)\bImported Machines\b",
    r"(?i)\bExportmanager\b",
    r"(?i)\bBusiness Unit Manager\b",
    r"(?i)\bExec Assistant\b",
    r"(?i)\bCosmetic Manufacturer\b",
    r"(?i)\bExport Assistant\b",
    r"(?i)Export",
    r"(?i)Import",
    r"(?i)Manufacturer",
    r"(?i)\bHead Of Supplies\b",
    r"(?i)\bDistribution Engineer\b",
    r"(?i)\bMedical Industry\b",
    r"(?i)\bRegenova\b",
    r"(?i)\bSenior Business Services Manager\b",
    r"(?i)\bBusiness & Management\b",
    r"(?i)\bSenior Executive\b",
    r"(?i)\bQuality Manager\b",
    r"(?i)\bHead Of Asia Pacific\b",
    r"(?i)\bHead Manager\b",
    r"(?i)\bManpower Supply\b",
    r"(?i)Purchasing",
    r"(?i)\bDoo\b",
    r"(?i)\bMedical Manager\b",
    r"(?i)\bDeputy Head Of Ir\b",
    r"(?i)\bMba\b",
    r"(?i)\bOperation Manager\b",
    r"(?i)\bAccount Supervisor\b",
    r"(?i)\bPurchasing Officer\b",
    r"(?i)\bDeputyoperationmanager\b",
    r"(?i)\bBba In Finance\b",
    r"(?i)\bCompliance Manager\b",
    r"(?i)\bSpecial Envoy On Trade & Investment\b",
    r"(?i)\bInformation Systems Manager\b",
    r"(?i)\bFinance Manager\b",
    r"(?i)\bInternational Trade\b",
    r"(?i)\bInteriors Motifs\b",
    r"(?i)\bPurchaser\b",
    r"(?i)\bSupply Chain Manager\b",
    r"(?i)\bOperational Manager\b",
    r"(?i)\bHead Of Global Technical Support Gxr Solutions\b",
    r"(?i)\bCapital Markets\b",
    r"(?i)\bOlson Ltd\b",
    r"(?i)\bAmbassador Of Bioskin Dermolife\b",
    r"(?i)\bPharmaceuticals\b",
    r"(?i)\bHr Admin Or SalaryExpenses\b",
    r"(?i)\bLecturerTechnologist\b",
    r"(?i)\bUs Western Manager\b",
    r"(?i)\bHr\b",
    r"(?i)\bWholesale Buyer\b",
    r"(?i)\bManager Officer\b",
    r"(?i)\bPharmaceutical\b",
    r"(?i)\bMgr Exec Strategic Account - Skm\b",
    r"(?i)\bMember Manager\b",
    r"(?i)\bLogistic Agency For Relife\b",
    r"(?i)\bCustomer Relations Manager\b",
    r"(?i)\bBuyer\b",
    r"(?i)\bSenior Buyer\b",
    r"(?i)\bAi Application In Aesthetic Medicine\b",
    r"(?i)\bRelife France\b",
    r"(?i)\bGlobal Head Of Beauty\b",
    r"(?i)\bBanking\b",
    r"(?i)\bMeg Ambassador\b",
    r"(?i)\bAudit Manager\b",
    r"(?i)\bHead Of Corporate Finance & Development\b",
    r"(?i)\bBusiness Relations Manager\b",
    r"(?i)\bBuilder Company\b",
    r"(?i)\bEmerging Tech\b",
    r"(?i)\bAssociate Manager\b",
    r"(?i)\bAssociate Media Connections PlannerBuyer\b",
    r"(?i)\bInvestment Associate\b",
    r"(?i)\bBuyers\b",
    r"(?i)\bShipping-&-Receiving Supervisor\b",
    r"(?i)\bWarehouse Supervisor\b",
    r"(?i)\bSoftware\b",
    r"(?i)\bSkin Care Brand\b",
    r"(?i)\bSurgeon Recruiter\b",
    r"(?i)\bRecruiting Coordinator\b",
]

# Exact matches that should be updated
company_manager_exact_matches = {
    'Company Manager',
    'Company Director',
    'Corporate Manager',
    'General Manager of Company',
    'Business Manager',
    'Executive Manager',
    'Chief Manager',
    'Manager of Company',
    'Manager of the Company',
    'Manager',
    'Pharma Industry',
    'Retail Chains',
    'Specialized Store/Concept Store',
    'Industry',
    'Business',
    'Manger',
    'Executive',
    'Director Of Operations',
    'Operations Director',
    'Gerant',
    'Country Manager',
    'Operations',
    'Company',
    'Directeur',
    'Directeur',
    'Director',
    'director',
    'Senior Associate',
    'Sr  Associate',
    'Director Of Customer Successtset',
    'Girector General',
    'Medical Equipment',
    'Purchase Specialist',
    'Travel Coordinator',
    'Travel Management',
    'Travel Agent',
    'Director Finance Treasury',
    'Director Of Strategic Partnerships',
    'Director Client Partnerships',
    'Director Of Information Technology',
    'Middle East Director',
    'Us Director',
    'Director Of Corp Development',
    'Country Director',
    'Director Of Professional Relations',
    'Medical Contracts Director',
    'Ict Director',
    'Board Director',
    'Manager Director',
    'Sr  Director',
    'Managing Directo',
    'Business Team Director',
    'Director Of Corporate Relations',
    'Overseas Business Department Manager',
    'International Director',
    'Medytox',
    'Technology Transfer Director',
    'Manager Of New Business Segments',
    'Direcctor',
    'Medical Company',
    'Managers',
    'Director Finance',
    'Ict Manager',
    'Sr  Manager Partner Relations',
    'Opperations',
    'Enhibitor',
    'Managing Dir Shield Network',
    'District Manager',
    'Managing Dir Shield Network',
    'Director Of International Cooperation',
    'International Relations',
    'Fillmed Greece',
    'Group Business Director',
    'Sustainability Executive',
    'Biotechnology Hydrogel',
    'Information Security Officer',
    'Corporate Management',
    'Customer Solution Officer',
    'Global  Latin America',
    'Managing DirectorFounder',
    'Regional Head Of Medical Equipment',
    'Head Of Information Technology',
    'Information Technology Director',
    'Co-Director & Manager',
    'DIRECTOR',
    'People & Culture Manager',
    'Specialized Store Concept Store',
    'Board Member',
    'Board of Director',
    'CPA - Treasurer',
    'Director HCP Advocacy',
    'Director Industry Outreach',
    'Director Latin America & Caribbean Islands',
    'Director of Customer Engagement',
    'Director of LATAM Relations',
    'Director of Partnerships',
    'Diretora',
    'District Manager SkinMedica',
    'District Manager FA',
    'Head of Finance',
    'MAC Director',
    'Management Staff',
    'Manager MAX Platform',
    'Manegment Staff',
    'Mgr',
    'Mgr Sr Dev - BOTOX Cosmetic',
    'Premier',
    'Recens USA',
    'Senior Acct Exec',
    'Treasurer & Director',
    'Director Mergers & Acquisitions',
    'Sr Director - Medical Aesthetics Gbu',
    'Fractional Executive',
    'Talent Acquisition- Dentist& Field Staff',
    'Director Dermatology Business',
    'Director Dermatology Business Texas & Ok North',
    'Director Of Physician Compensation',
    'District Manager- Dermatology',
    'Manager Information Technology At Md Alliance Solutions Llc Advanced Dermatology Pc',
    'Physician Finance Officer',
    'Site Manager - General Surgery',
    'Financial Assistant',
    'ASM North Texas',
    'Area Director',
    'Asset Strategy Leader Aesthetics',
    'Assoc Director Search & Evaluation Aesthetics',
    'Asst Mgr',
    'B S',
    'BA',
    'BBA',
    'BENEV',
    'BS',
    'Bachelor',
    'Bachelor of Science in Business',
    'Big D',
    'CPO',
    'Chief Accounts Officer',
    'Chief Culture Coordinator',
    'Chief Evangelist',
    'Chief Growth Officer',
    'Chief Revenue Off',
    'Chief Strategy Officer',
    'Chief Revenue Officer Of Buildmyhealth',
    'Chief Technology officer',
    'Client Support Manager',
    'Corporate Account Director',
    'Corporate Accounts Manager',
    'Cosmetic Peel Company',
    'Customer Success Manager',
    'Customer Success Specialist',
    'Customer Success Team',
    'CRO',
    'Dir Strat Accts',
    'Dir Strategic Accounts',
    'Director Ax Customer Engagement -East',
    'Director Biostimulators',
    'Director Clinical Development Allergan Aesthetic Medicine',
    'Director Corporate Accounts',
    'Director Customer Engagement',
    'Director Customer Engagement -West',
    'Director Customer Engagement East',
    'Director Customer Loyalty',
    'Director Development & Acquisitions',
    'Director External Innovation',
    'Director Field Service Engineer',
    'Director Finance Accounting',
    'Director National Accounts',
    'Director Of Strategic Accounts',
    'Director Portfolio & Strategic Implementation',
    'Director Portfolio Programs',
    'Director Portfolio Programs & National Conventions',
    'Director Strategic Accounts & Physicians',
    'Director Strategic Accounts - Medic',
    'Director Strategic Accounts - Medica',
    'Director Technical Services',
    'Director of Customer Affairs',
    'Director of Customer Experience',
    'Director of National Accounts',
    'Director of Recruitment',
    'District Manager FA- Austin TX',
    'District Manager- National Accounts',
    'Emerald Specialist',
    'Exec Dir Professional Relations',
    'Exetcutive',
    'Experience Manager',
    'Financial Director',
}

# Define patterns (these should NOT be changed)
company_manager_exclusions = {
    'Resident',
    'resident',
    'student',
    'Trainee',
    'Resident Doctor',
    'Resident Physician',
    'Intern',
    'intern',
    'Medical Intern',
    'Fellow',
    'fellow',
    'Clinical Fellow',
    'Medical Student',
    'Clinical Trainee',
    'Trainee Doctor',
    'Trainee Physician',
    'Junior Doctor',
    'Postgraduate Trainee',
    'Aesthetic Fellow',
    'Aesthetic Trainee',
    'Aesthetic Medicine Fellow',
    'Aesthetic Resident',
    'Marketing Director',
    'Operations Project Manager',
    'Registered Nurse Program Manager-Clinical Operations',
    'Director Of Clinical Operations',
    'Rn Bsn Phn Mba',
    'Chief Of Operations & Practice Manager',
    'RN BSN MBA'
 }

# Create a mask for Company Manager
mask_company_manager = df['speciality'].str.contains('|'.join(company_manager_variants), case = False,
                                                          na = False, regex = True) | \
                            df['speciality'].isin(company_manager_exact_matches)
mask_company_manager_exclusions = df['speciality'].isin(company_manager_exclusions)

# Final mask: Select Company Manager
mask_company_manager_final = mask_company_manager & ~mask_company_manager_exclusions

# Store the original values that will be replaced
original_company_manager_values = df.loc[mask_company_manager_final, 'speciality'].unique()

# Update the speciality column based on exact matches
df.loc[mask_company_manager_final, 'speciality'] = 'Company Manager'

# Check AFTER updating
print(colored("\nUnique values AFTER updating: Company Manager", 'green'))
print(df.loc[mask_company_manager_final, 'speciality'].unique())

# GroupBy to count how many records were replaced by the new value
grouped_company_manager_values = df.loc[mask_company_manager_final, 'speciality'].value_counts()

# Print the exact replacements
print(colored("\nReplaced Values: Company Manager", "cyan"))
for original_company_manager_value in original_company_manager_values:
    print(f"✅ {original_company_manager_value} → Company Manager")

# GroupBy after replacement (to show the new value)
print(colored("\nGroupBy counts AFTER replacing with Company Manager:", 'red'))
print(grouped_company_manager_values)

# Print summary
matched_count_company_manager = mask_company_manager_final.sum()

# Print results
print(
    colored(
        f"\nTotal values matched and changed (Stage 1) to Company Manager: "
        f"{matched_count_company_manager}",
        'red'))