"""
HubSpot audit bridge - thin adapter to connect HubSpot operations to the shared AuditLogger.
"""

import logging
from typing import Any, Dict, Optional

from .core import HubSpotIntegration

logger = logging.getLogger(__name__)


class HubSpotAuditIntegration:
    """
    Audit adapter for HubSpot operations.
    Provides HubSpot-specific metadata formatting for the shared AuditLogger.
    """

    def __init__(self, audit_logger: Any, hs_integration: HubSpotIntegration):
        """
        Initialize HubSpot audit integration.

        Args:
            audit_logger: Shared AuditLogger instance
            hs_integration: HubSpot integration instance
        """
        self.audit_logger = audit_logger
        self.hs_integration = hs_integration

    async def audit_workflow_start(
        self,
        workflow_name: str,
        config: Dict[str, Any],
        input_count: int,
        user: Optional[str] = None
    ):
        """Audit workflow start with HubSpot-specific metadata."""
        metadata = {
            'portal_id': self.hs_integration.credentials.portal_id,
            'user_email': user or self.hs_integration.credentials.user_email,
            'workflow_config': config,
            'input_record_count': input_count,
            'api_limits': {
                'core_remaining': self.hs_integration.api_limits.core_api_remaining,
                'daily_remaining': self.hs_integration.api_limits.daily_remaining
            }
        }

        await self.audit_logger.log_event(
            event_type='workflow_start',
            entity_type='hubspot_workflow',
            entity_id=workflow_name,
            action='start',
            metadata=metadata,
            user=user or self.hs_integration.credentials.user_email
        )

    async def audit_workflow_completion(
        self,
        workflow_name: str,
        result: Dict[str, Any],
        user: Optional[str] = None
    ):
        """Audit workflow completion with results."""
        metadata = {
            'portal_id': self.hs_integration.credentials.portal_id,
            'user_email': user or self.hs_integration.credentials.user_email,
            'workflow_result': result,
            'api_limits_after': {
                'core_remaining': self.hs_integration.api_limits.core_api_remaining,
                'daily_remaining': self.hs_integration.api_limits.daily_remaining
            }
        }

        await self.audit_logger.log_event(
            event_type='workflow_complete',
            entity_type='hubspot_workflow',
            entity_id=workflow_name,
            action='complete',
            metadata=metadata,
            user=user or self.hs_integration.credentials.user_email
        )

    async def audit_api_call(
        self,
        endpoint: str,
        method: str,
        status_code: int,
        request_data: Optional[Dict[str, Any]] = None,
        response_data: Optional[Dict[str, Any]] = None,
        error: Optional[str] = None
    ):
        """Audit individual API calls for compliance tracking."""
        metadata = {
            'portal_id': self.hs_integration.credentials.portal_id,
            'endpoint': endpoint,
            'method': method,
            'status_code': status_code,
            'error': error,
            'rate_limits': {
                'remaining': self.hs_integration.api_limits.core_api_remaining,
                'max': self.hs_integration.api_limits.core_api_max
            }
        }

        # Add request summary (not full data for security)
        if request_data:
            metadata['request_summary'] = {
                'records_count': len(request_data.get('inputs', [])) if 'inputs' in request_data else 1
            }

        await self.audit_logger.log_event(
            event_type='api_call',
            entity_type='hubspot_api',
            entity_id=endpoint,
            action=method.lower(),
            metadata=metadata,
            user=self.hs_integration.credentials.user_email
        )

    async def audit_data_export(
        self,
        object_name: str,
        record_count: int,
        properties: list,
        filters: Optional[Dict[str, Any]] = None,
        user: Optional[str] = None
    ):
        """Audit data export operations."""
        metadata = {
            'portal_id': self.hs_integration.credentials.portal_id,
            'object_name': object_name,
            'record_count': record_count,
            'properties_requested': properties,
            'filters_applied': filters or {},
            'export_timestamp': self.audit_logger._get_timestamp()
        }

        await self.audit_logger.log_event(
            event_type='data_export',
            entity_type='hubspot_object',
            entity_id=object_name,
            action='export',
            metadata=metadata,
            user=user or self.hs_integration.credentials.user_email
        )

    async def audit_data_import(
        self,
        object_name: str,
        record_count: int,
        operation: str,
        success_count: int,
        error_count: int,
        user: Optional[str] = None
    ):
        """Audit data import operations."""
        metadata = {
            'portal_id': self.hs_integration.credentials.portal_id,
            'object_name': object_name,
            'total_records': record_count,
            'operation': operation,  # CREATE_AND_UPDATE, CREATE_ONLY, UPDATE_ONLY
            'success_count': success_count,
            'error_count': error_count,
            'import_timestamp': self.audit_logger._get_timestamp()
        }

        await self.audit_logger.log_event(
            event_type='data_import',
            entity_type='hubspot_object',
            entity_id=object_name,
            action='import',
            metadata=metadata,
            user=user or self.hs_integration.credentials.user_email
        )

    async def audit_record_merge(
        self,
        object_name: str,
        primary_id: str,
        merged_ids: list,
        user: Optional[str] = None
    ):
        """Audit record merge operations."""
        metadata = {
            'portal_id': self.hs_integration.credentials.portal_id,
            'object_name': object_name,
            'primary_record_id': primary_id,
            'merged_record_ids': merged_ids,
            'merge_count': len(merged_ids)
        }

        await self.audit_logger.log_event(
            event_type='record_merge',
            entity_type='hubspot_object',
            entity_id=primary_id,
            action='merge',
            metadata=metadata,
            user=user or self.hs_integration.credentials.user_email
        )

    async def audit_association_created(
        self,
        from_object: str,
        from_id: str,
        to_object: str,
        to_id: str,
        association_type: str,
        user: Optional[str] = None
    ):
        """Audit association creation."""
        metadata = {
            'portal_id': self.hs_integration.credentials.portal_id,
            'from_object': from_object,
            'from_id': from_id,
            'to_object': to_object,
            'to_id': to_id,
            'association_type': association_type
        }

        await self.audit_logger.log_event(
            event_type='association_created',
            entity_type='hubspot_association',
            entity_id=f"{from_object}:{from_id}->{to_object}:{to_id}",
            action='create',
            metadata=metadata,
            user=user or self.hs_integration.credentials.user_email
        )

    async def create_snapshot(
        self,
        snapshot_data: Dict[str, Any],
        description: str,
        user: Optional[str] = None
    ) -> str:
        """Create a snapshot for rollback capability."""
        # Add HubSpot-specific metadata
        snapshot_data['portal_id'] = self.hs_integration.credentials.portal_id
        snapshot_data['api_version'] = 'v3'

        return await self.audit_logger.create_snapshot(
            snapshot_data=snapshot_data,
            description=description,
            user=user or self.hs_integration.credentials.user_email
        )

    async def get_compliance_report(
        self,
        start_date: Optional[str] = None,
        end_date: Optional[str] = None,
        compliance_framework: str = 'SOX'
    ) -> Dict[str, Any]:
        """
        Get compliance report with HubSpot-specific checks.

        Args:
            start_date: Report start date
            end_date: Report end date
            compliance_framework: Framework to check against

        Returns:
            Compliance report dictionary
        """
        # Get base report from audit logger
        base_report = await self.audit_logger.generate_compliance_report(
            start_date=start_date,
            end_date=end_date,
            compliance_framework=compliance_framework
        )

        # Add HubSpot-specific compliance checks
        hubspot_checks = {
            'data_residency': self._check_data_residency(),
            'api_usage_compliance': self._check_api_usage_compliance(),
            'field_encryption': self._check_field_encryption()
        }

        base_report['hubspot_specific_checks'] = hubspot_checks

        return base_report

    def _check_data_residency(self) -> Dict[str, Any]:
        """Check data residency compliance."""
        # HubSpot data centers are in US and EU
        return {
            'compliant': True,
            'details': 'HubSpot data stored in approved regions',
            'portal_id': self.hs_integration.credentials.portal_id
        }

    def _check_api_usage_compliance(self) -> Dict[str, Any]:
        """Check API usage is within limits."""
        limits = self.hs_integration.api_limits

        # Check if we're staying well under limits
        usage_percentage = (
            (limits.core_api_max - limits.core_api_remaining) / limits.core_api_max * 100
            if limits.core_api_max > 0 else 0
        )

        return {
            'compliant': usage_percentage < 80,  # Alert if over 80% usage
            'usage_percentage': usage_percentage,
            'details': f"API usage at {usage_percentage:.1f}% of limit"
        }

    def _check_field_encryption(self) -> Dict[str, Any]:
        """Check if sensitive fields are properly handled."""
        # This would check if PII fields are being encrypted in logs
        return {
            'compliant': True,
            'details': 'Sensitive fields excluded from audit logs'
        }
