"""Coverage mapper service for business insurance coverage types."""
from typing import Dict, Type, Any, Optional, List
from sqlmodel import SQLModel

from app.models.BusinessOwnerPolicyModel import BusinessOwnerPolicyModel
from app.models.Commercialautomodel import CommercialAutoModel
from app.models.CommercialPropertyModel import CommercialPropertyModel
from app.models.cyberliabilityinsurance import Cyberliability
from app.models.GroupHealthModel import GroupHealthModel
from app.models.GroupLifeModel import GroupLifeModel
from app.models.OceanMarineModel import OceanMarineModel
from app.models.professionalliabilityinsurance import ProfessionalLiability
from app.models.UmbrellaInsuranceModel import UmbrellaInsuranceModel
from app.models.WorkersCompensationModel import WorkersCompensationModel


class CoverageMapper:
    """Maps coverage types to their corresponding models."""
    
    COVERAGE_MODEL_MAP: Dict[str, Type[SQLModel]] = {
        "bop": BusinessOwnerPolicyModel,
        "auto": CommercialAutoModel,
        "property": CommercialPropertyModel,
        "cyber": Cyberliability,
        "gl": None,  # General Liability - handled separately
        "groupHealth": GroupHealthModel,
        "groupLife": GroupLifeModel,
        "ocean": OceanMarineModel,
        "eando": ProfessionalLiability,
        "umbrella": UmbrellaInsuranceModel,
        "workers": WorkersCompensationModel,
    }
    
    @classmethod
    def get_model_for_coverage(cls, coverage_type: str) -> Optional[Type[SQLModel]]:
        """Get the model class for a coverage type."""
        return cls.COVERAGE_MODEL_MAP.get(coverage_type)
    
    @classmethod
    def create_coverage_record(cls, coverage_type: str, coverage_data: Dict[str, Any], business_info: Dict[str, Any]) -> Optional[SQLModel]:
        """Create a coverage record for the specified type."""
        model_class = cls.get_model_for_coverage(coverage_type)
        if not model_class:
            print(f"No model found for coverage type: {coverage_type}")
            return None
        
        try:
            mapped_data = cls._map_business_fields(coverage_type, coverage_data, business_info)
            print(f"Creating {coverage_type} record with data keys: {list(mapped_data.keys())}")
            
            # 1. Encrypt sensitive fields if the model uses get_encrypted_fields (BaseRepository pattern)
            if hasattr(model_class, 'get_encrypted_fields'):
                from app.core.encryption import encryption_service
                encrypted_fields = model_class().get_encrypted_fields()
                for field in encrypted_fields:
                    if field in mapped_data and mapped_data[field]:
                        mapped_data[field] = encryption_service.encrypt(str(mapped_data[field]))
            
            record = model_class(**mapped_data)
            
            # 2. Encrypt sensitive fields if the model uses encrypt_sensitive_data (Active Record pattern)
            if hasattr(record, 'encrypt_sensitive_data'):
                record.encrypt_sensitive_data()
                
            return record
        except Exception as e:
            print(f"Error creating {coverage_type} record: {e}")
            print(f"Available data keys: {list(mapped_data.keys()) if 'mapped_data' in locals() else 'N/A'}")
            return None
    
    @classmethod
    def _map_business_fields(cls, coverage_type: str, coverage_data: Dict[str, Any], business_info: Dict[str, Any]) -> Dict[str, Any]:
        """Map business info fields to coverage-specific fields."""
        mapped_data = coverage_data.copy()
        
        common_mappings = cls._get_common_mappings(business_info)
        specific_mappings = cls._get_coverage_specific_mappings(coverage_type, business_info)
        all_mappings = {**common_mappings, **specific_mappings}
        
        cls._apply_mappings(mapped_data, all_mappings)
        cls._add_transaction_and_defaults(coverage_type, mapped_data)
        
        print(f"Final mapped data for {coverage_type}: {mapped_data}")
        return mapped_data
    
    @classmethod
    def _get_common_mappings(cls, business_info: Dict[str, Any]) -> Dict[str, Any]:
        """Get common field mappings for all coverage types."""
        address_parts = [
            business_info.get('street', ''),
            business_info.get('city', ''),
            business_info.get('state', ''),
            business_info.get('zip_code', '')
        ]
        business_address = ', '.join(filter(None, address_parts))
        
        return {
            "business_name": business_info.get("business_name"),
            "contact_name": business_info.get("owner_name"),
            "email_address": business_info.get("owner_email"),
            "phone_number": business_info.get("owner_mobile"),
            "business_address": business_address,
            "city": business_info.get("city"),
            "state": business_info.get("state"),
            "zip_code": business_info.get("zip_code"),
        }
    
    @classmethod
    def _get_coverage_specific_mappings(cls, coverage_type: str, business_info: Dict[str, Any]) -> Dict[str, Any]:
        """Get coverage-specific field mappings."""
        mapping_methods = {
            "bop": cls._get_bop_mappings,
            "auto": cls._get_auto_mappings,
            "property": cls._get_property_mappings,
            "cyber": cls._get_cyber_mappings,
            "workers": cls._get_workers_mappings,
            "eando": cls._get_eando_mappings,
            "ocean": cls._get_ocean_mappings,
            "umbrella": cls._get_umbrella_mappings,
        }
        
        if coverage_type in ["groupHealth", "groupLife"]:
            return cls._get_group_mappings(business_info)
        
        method = mapping_methods.get(coverage_type)
        return method(business_info) if method else {}
    
    @classmethod
    def _get_bop_mappings(cls, business_info: Dict[str, Any]) -> Dict[str, Any]:
        """Get BOP-specific mappings."""
        return {
            "type_of_business": business_info.get("industry"),
            "business_entity_type": business_info.get("business_type"),
            "years_in_business": cls._safe_int(business_info.get("est_year")),
            "annual_revenue": cls._safe_float(business_info.get("annual_revenue")),
            "number_of_employees": 1,
        }
    
    @classmethod
    def _get_auto_mappings(cls, business_info: Dict[str, Any]) -> Dict[str, Any]:
        """Get Auto-specific mappings."""
        return {
            "type_of_business": business_info.get("industry"),
            "business_entity_type": business_info.get("business_type"),
            "years_in_business": cls._safe_int(business_info.get("est_year")),
            "annual_revenue": cls._safe_float(business_info.get("annual_revenue")),
        }
    
    @classmethod
    def _get_property_mappings(cls, business_info: Dict[str, Any]) -> Dict[str, Any]:
        """Get Property-specific mappings."""
        return {
            "business_type": business_info.get("business_type"),
            "years_in_business": cls._safe_int(business_info.get("est_year")),
        }
    
    @classmethod
    def _get_cyber_mappings(cls, business_info: Dict[str, Any]) -> Dict[str, Any]:
        """Get Cyber-specific mappings."""
        return {
            "type_of_business": business_info.get("industry"),
            "business_entity_type": business_info.get("business_type"),
            "years_in_business": cls._safe_int(business_info.get("est_year")),
            "annual_revenue": cls._safe_float(business_info.get("annual_revenue")),
        }
    
    @classmethod
    def _get_workers_mappings(cls, business_info: Dict[str, Any]) -> Dict[str, Any]:
        """Get Workers-specific mappings."""
        return {
            "type_of_business": business_info.get("industry"),
            "business_entity_type": business_info.get("business_type"),
            "years_in_business": cls._safe_int(business_info.get("est_year")),
            "fein": business_info.get("tax_id"),
            "number_of_employees": 1,
        }
    
    @classmethod
    def _get_eando_mappings(cls, business_info: Dict[str, Any]) -> Dict[str, Any]:
        """Get E&O-specific mappings."""
        return {
            "business_type": business_info.get("industry"),
            "years_in_business": cls._safe_int(business_info.get("est_year")),
            "annual_revenue": cls._safe_float(business_info.get("annual_revenue")),
            "number_of_employees": 1,
        }
    
    @classmethod
    def _get_group_mappings(cls, business_info: Dict[str, Any]) -> Dict[str, Any]:
        """Get Group Health/Life-specific mappings."""
        return {
            "company_name": business_info.get("business_name"),
            "industry": business_info.get("industry"),
            "ein": business_info.get("tax_id"),
            "contact_person": business_info.get("owner_name"),
            "contact_phone": business_info.get("owner_mobile"),
            "contact_email": business_info.get("owner_email"),
            "street": business_info.get("street"),
        }
    
    @classmethod
    def _get_ocean_mappings(cls, business_info: Dict[str, Any]) -> Dict[str, Any]:
        """Get Ocean-specific mappings."""
        return {
            "annual_cargo_value": cls._safe_float(business_info.get("annual_revenue")),
        }
    
    @classmethod
    def _get_umbrella_mappings(cls, business_info: Dict[str, Any]) -> Dict[str, Any]:
        """Get Umbrella-specific mappings."""
        return {
            "business_type": business_info.get("business_type"),
            "years_in_business": cls._safe_int(business_info.get("est_year")),
        }
    
    @classmethod
    def _safe_int(cls, value: Any) -> int:
        """Safely convert value to int."""
        return int(value) if value else 0
    
    @classmethod
    def _safe_float(cls, value: Any) -> float:
        """Safely convert value to float."""
        return float(value) if value else 0.0
    
    @classmethod
    def _apply_mappings(cls, mapped_data: Dict[str, Any], mappings: Dict[str, Any]) -> None:
        """Apply field mappings to mapped_data."""
        for target_field, source_value in mappings.items():
            if target_field not in mapped_data and source_value is not None:
                mapped_data[target_field] = source_value
    
    @classmethod
    def _add_transaction_and_defaults(cls, coverage_type: str, mapped_data: Dict[str, Any]) -> None:
        """Add transaction number and required defaults."""
        if "transaction_no" not in mapped_data:
            from app.utils.transaction_generator import generate_transaction_number
            mapped_data["transaction_no"] = generate_transaction_number(coverage_type)
        
        cls._add_required_defaults(coverage_type, mapped_data)
    
    @classmethod
    def _add_required_defaults(cls, coverage_type: str, mapped_data: Dict[str, Any]) -> None:
        """Add required default values for specific coverage types."""
        if coverage_type == "bop":
            cls._add_bop_defaults(mapped_data)
        elif coverage_type == "auto":
            cls._add_auto_defaults(mapped_data)
        elif coverage_type == "property":
            cls._add_property_defaults(mapped_data)
        elif coverage_type == "cyber":
            cls._add_cyber_defaults(mapped_data)
        elif coverage_type == "workers":
            cls._add_workers_defaults(mapped_data)
        elif coverage_type == "eando":
            cls._add_eando_defaults(mapped_data)
        elif coverage_type in ["groupHealth", "groupLife"]:
            cls._add_group_defaults(mapped_data)
        elif coverage_type == "ocean":
            cls._add_ocean_defaults(mapped_data)
        elif coverage_type == "umbrella":
            cls._add_umbrella_defaults(mapped_data)
    
    @classmethod
    def _add_bop_defaults(cls, mapped_data: Dict[str, Any]) -> None:
        """Add BOP required defaults."""
        from datetime import date
        
        defaults = {
            "property_owned_or_leased": mapped_data.get("tenure", "Own"),
            "square_footage": cls._safe_int(mapped_data.get("sqft", 1000)),
            "building_construction_type": mapped_data.get("construction", "Frame"),
            "year_built": cls._safe_int(mapped_data.get("yearBuilt", 2000)),
            "business_personal_property_value": cls._safe_float(mapped_data.get("bppValue", 100000)),
            "prior_claims_last_5_years": False,
            "desired_coverage_start_date": date.today(),
            "desired_property_coverage_limit": 1000000.0,
            "desired_general_liability_coverage_limit": 1000000.0,
        }
        
        for field, default_value in defaults.items():
            if field not in mapped_data:
                mapped_data[field] = default_value
        
        if "property_addresses" not in mapped_data:
            mapped_data["property_addresses"] = [mapped_data.get("address", "")]
        if "security_safety_features" not in mapped_data:
            mapped_data["security_safety_features"] = mapped_data.get("features", [])
    
    @classmethod
    def _add_auto_defaults(cls, mapped_data: Dict[str, Any]) -> None:
        """Add Auto required defaults."""
        from datetime import date
        
        defaults = {
            "number_of_vehicles": cls._safe_int(mapped_data.get("numberOfVehicles", 1)),
            "vehicle_use_type": mapped_data.get("vehicleUseType", "business"),
            "radius_of_operation": mapped_data.get("radius", "local"),
            "vehicles_cross_state_lines": mapped_data.get("crossState") == "yes",
            "garaging_zip_codes": mapped_data.get("garagingZips", ""),
            "mvr_violations_past_3_years": mapped_data.get("mvrViolations") == "yes",
            "accidents_claims_past_5_years": mapped_data.get("accidentsClaims") == "yes",
            "current_auto_insurance": mapped_data.get("hasCurrentAutoInsurance") == "yes",
            "desired_policy_start_date": date.today(),
            "desired_coverage_types": "Liability, Comprehensive, Collision",
            "desired_coverage_limits": "1000000/1000000/1000000",
            "comprehensive_collision_deductibles": "500/500",
            "hired_non_owned_coverage_needed": False,
            "special_equipment_on_vehicles": False,
        }
        
        for field, default_value in defaults.items():
            if field not in mapped_data:
                mapped_data[field] = default_value
        
        if "vehicle_list" not in mapped_data:
            vehicles = mapped_data.get("vehicles", [])
            mapped_data["vehicle_list"] = str(vehicles) if vehicles else "[]"
        
        if "driver_list" not in mapped_data:
            drivers = mapped_data.get("drivers", [])
            mapped_data["driver_list"] = str(drivers) if drivers else "[]"
    
    @classmethod
    def _add_cyber_defaults(cls, mapped_data: Dict[str, Any]) -> None:
        """Add Cyber required defaults."""
        from datetime import date
        
        defaults = {
            "number_of_employees": 1,
            "number_of_records_stored": cls._safe_int(mapped_data.get("recordsCount", 1000)),
            "use_of_cloud_providers": mapped_data.get("useCloud") == "yes",
            "percentage_business_online": cls._safe_float(mapped_data.get("onlinePct", 50)),
            "mfa_used": mapped_data.get("mfa") == "yes",
            "data_encryption": mapped_data.get("encryption") == "yes",
            "endpoint_protection": mapped_data.get("endpoint") == "yes",
            "cybersecurity_training": mapped_data.get("training") == "yes",
            "prior_cyber_incidents": False,
            "desired_coverage_limit": 1000000.0,
            "desired_policy_start_date": date.today(),
        }
        
        for field, default_value in defaults.items():
            if field not in mapped_data:
                mapped_data[field] = default_value
        
        if "types_of_sensitive_data" not in mapped_data:
            sensitive = mapped_data.get("sensitive", {})
            mapped_data["types_of_sensitive_data"] = [k for k, v in sensitive.items() if v]
        
        if "cybersecurity_frameworks" not in mapped_data:
            frameworks = mapped_data.get("frameworks", {})
            mapped_data["cybersecurity_frameworks"] = [k for k, v in frameworks.items() if v]
    
    @classmethod
    def _add_workers_defaults(cls, mapped_data: Dict[str, Any]) -> None:
        """Add Workers required defaults."""
        from datetime import date
        
        defaults = {
            "number_of_employees": 1,
            "independent_contractors": mapped_data.get("has1099") == "Yes",
            "number_of_contractors": cls._safe_int(mapped_data.get("indepCount", 0)),
            "temp_seasonal_volunteer_workers": mapped_data.get("seasonal") == "Yes",
            "past_workers_comp_claims": False,
            "desired_effective_date": date.today(),
        }
        
        for field, default_value in defaults.items():
            if field not in mapped_data:
                mapped_data[field] = default_value
        
        if "employee_job_classifications" not in mapped_data:
            jobs = mapped_data.get("jobs", [])
            mapped_data["employee_job_classifications"] = str(jobs) if jobs else "[]"
        
        if "annual_payroll_by_classification" not in mapped_data:
            jobs = mapped_data.get("jobs", [])
            payroll_data = {job.get("role", "General"): job.get("payroll", "0") for job in jobs}
            mapped_data["annual_payroll_by_classification"] = str(payroll_data)
        
        if "states_of_operation" not in mapped_data:
            jobs = mapped_data.get("jobs", [])
            states = set()
            for job in jobs:
                states.update(job.get("states", []))
            mapped_data["states_of_operation"] = ",".join(states) if states else "AL"
    
    @classmethod
    def _add_property_defaults(cls, mapped_data: Dict[str, Any]) -> None:
        """Add Property required defaults."""
        from datetime import date
        
        defaults = {
            "type_of_business": mapped_data.get("type_of_business", "Retail"),
            "business_entity_type": mapped_data.get("business_entity_type", "LLC"),
            "annual_revenue": cls._safe_float(mapped_data.get("annual_revenue", 500000)),
            "number_of_employees": 1,
            "number_of_locations": 1,
            "property_addresses": mapped_data.get("business_address", ""),
            "ownership_status": "Own",
            "building_use": "Office",
            "building_construction_type": "Frame",
            "year_built": cls._safe_int(mapped_data.get("yearBuilt", 2000)),
            "square_footage": cls._safe_int(mapped_data.get("sqft", 5000)),
            "building_replacement_value": 500000.0,
            "contents_inventory_value": 100000.0,
            "business_interruption_coverage_needed": False,
            "business_income_annual": cls._safe_float(mapped_data.get("annual_revenue", 500000)),
            "security_features": "Basic",
            "distance_to_fire_hydrant_ft": 500,
            "distance_to_fire_station_miles": 2.0,
            "existing_property_insurance": False,
            "prior_claims_last_5_years": False,
            "desired_coverage_start_date": date.today(),
            "desired_deductible": 5000.0,
            "desired_coverage_limit": 1000000.0,
        }
        
        for field, default_value in defaults.items():
            if field not in mapped_data:
                mapped_data[field] = default_value
    
    @classmethod
    def _add_eando_defaults(cls, mapped_data: Dict[str, Any]) -> None:
        """Add E&O required defaults."""
        from datetime import date
        
        defaults = {
            "description_of_services": "Professional consulting services",
            "requested_coverage_limit": 1000000.0,
            "requested_deductible": 5000.0,
            "coverage_basis": "Claims Made",
            "retroactive_needed": True,
            "retroactive_date": date.today(),
            "prior_claims": False,
            "subcontracted_services": False,
            "subcontracted_percentage": 0.0,
            "coverage_for_contractors": False,
            "contracts_reviewed_legal": True,
            "professional_licenses": "Standard Business License",
            "desired_policy_start": date.today(),
        }
        
        for field, default_value in defaults.items():
            if field not in mapped_data:
                mapped_data[field] = default_value
    
    @classmethod
    def _add_group_defaults(cls, mapped_data: Dict[str, Any]) -> None:
        """Add Group Health/Life required defaults."""
        from datetime import date
        
        # Group Health specific
        if "industry_sic_code" not in mapped_data:
            mapped_data["industry_sic_code"] = "8999"
        if "number_of_employees" not in mapped_data:
            mapped_data["number_of_employees"] = 5
        if "number_of_employees_to_be_covered" not in mapped_data:
            mapped_data["number_of_employees_to_be_covered"] = 5
        if "type_of_coverage_requested" not in mapped_data:
            mapped_data["type_of_coverage_requested"] = "Medical"
        if "desired_coverage_start_date" not in mapped_data:
            mapped_data["desired_coverage_start_date"] = date.today()
        
        # Group Life specific
        if "industry_type" not in mapped_data:
            mapped_data["industry_type"] = "Professional Services"
        if "federal_tax_id" not in mapped_data:
            mapped_data["federal_tax_id"] = "00-0000000"
        if "company_address" not in mapped_data:
            mapped_data["company_address"] = mapped_data.get("business_address", "")
        if "type_of_group" not in mapped_data:
            mapped_data["type_of_group"] = "Employee Group"
        if "number_of_eligible_employees" not in mapped_data:
            mapped_data["number_of_eligible_employees"] = 5
        if "number_of_employees_to_be_insured" not in mapped_data:
            mapped_data["number_of_employees_to_be_insured"] = 5
        if "coverage_type_requested" not in mapped_data:
            mapped_data["coverage_type_requested"] = "Term Life"
        if "requested_effective_date" not in mapped_data:
            mapped_data["requested_effective_date"] = date.today()
        

    
    @classmethod
    def _add_ocean_defaults(cls, mapped_data: Dict[str, Any]) -> None:
        """Add Ocean Marine required defaults."""
        from datetime import date
        
        defaults = {
            "type_of_operation": "Import/Export",
            "description_of_goods": "General Merchandise",
            "value_per_shipment": 50000.0,
            "shipping_methods": "Container Ship",
            "countries_of_origin": "USA",
            "countries_of_destination": "International",
            "packaging_type": "Standard Container",
            "vessel_information": "Commercial Vessel",
            "own_vessel": False,
            "number_of_shipments_per_year": 12,
            "max_value_single_shipment": 100000.0,
            "past_claims_history": "None",
            "desired_policy_start_date": date.today(),
            "desired_coverage_types": "Cargo Coverage",
            "deductible_preference": 5000.0,
            "certificate_insurance_needed": False,
        }
        
        for field, default_value in defaults.items():
            if field not in mapped_data:
                mapped_data[field] = default_value
    
    @classmethod
    def _add_umbrella_defaults(cls, mapped_data: Dict[str, Any]) -> None:
        """Add Umbrella required defaults."""
        from datetime import date
        
        defaults = {
            "full_name": mapped_data.get("contact_name", "Business Owner"),
            "date_of_birth": "1980-01-01",
            "mobile_phone": mapped_data.get("phone_number", ""),
            "residential_address": mapped_data.get("business_address", ""),
            "state_of_residence": mapped_data.get("state", "AL"),
            "home_ownership": "Own",
            "homeowner_renters_provider": "State Farm",
            "owns_rental_property": False,
            "number_of_vehicles": 2,
            "auto_insurance_provider": "State Farm",
            "owns_boat_atv_rv": False,
            "teen_drivers_in_home": False,
            "high_risk_pets": False,
            "liability_claims_last_5_years": False,
            "annual_household_income": cls._safe_float(mapped_data.get("annual_revenue", 100000)),
            "total_net_worth": cls._safe_float(mapped_data.get("annual_revenue", 100000)) * 2,
            "desired_coverage_amount": 1000000.0,
            "preferred_contact_method": "Email",
        }
        
        for field, default_value in defaults.items():
            if field not in mapped_data:
                mapped_data[field] = default_value
    
    @classmethod
    def get_supported_coverages(cls) -> List[str]:
        """Get list of supported coverage types."""
        return list(cls.COVERAGE_MODEL_MAP.keys())


coverage_mapper = CoverageMapper()