import re
import logging
from typing import Tuple, Optional
from datetime import datetime, timedelta

logger = logging.getLogger(__name__)


class FraudDetector:
    def __init__(self, high_amount_threshold: int = 1000000):
        self.high_amount_threshold = high_amount_threshold
        self.velocity_tracker = {}
        logger.info(f"FraudDetector initialized with threshold: {high_amount_threshold}")
    
    def check_fraud(self, payment_data: dict, transaction_history: list = None) -> Tuple[bool, Optional[str]]:
        amount = payment_data.get("amount", 0)
        email = payment_data.get("email", "")
        
        if amount > self.high_amount_threshold:
            reason = f"Amount exceeds threshold: {amount} > {self.high_amount_threshold}"
            logger.warning(f"Fraud detected: {reason}")
            return True, reason
        
        if self._check_velocity(email, amount):
            reason = f"Velocity check failed: too many transactions from {email}"
            logger.warning(f"Fraud detected: {reason}")
            return True, reason
        
        card_number = payment_data.get("card_number", "")
        if self._is_suspicious_card_pattern(card_number):
            reason = "Suspicious card number pattern detected"
            logger.warning(f"Fraud detected: {reason}")
            return True, reason
        
        logger.info("Fraud check passed")
        return False, None
    
    def _check_velocity(self, email: str, amount: int) -> bool:
        current_time = datetime.utcnow()
        
        if email not in self.velocity_tracker:
            self.velocity_tracker[email] = []
            
        self.velocity_tracker[email] = [
            (ts, amt) for ts, amt in self.velocity_tracker[email]
            if current_time - ts < timedelta(hours=1)
        ]
        
        if len(self.velocity_tracker[email]) >= 5:
            return True
        
        total_amount = sum(amt for _, amt in self.velocity_tracker[email])
        if total_amount + amount > 5000000:
            return True
        
        self.velocity_tracker[email].append((current_time, amount))
        
        return False
    
    def _is_suspicious_card_pattern(self, card_number: str) -> bool:
        cleaned = re.sub(r"[\s-]", "", card_number)
        
        if len(set(cleaned)) == 1:
            return True
        
        if cleaned in "01234567890123456789":
            return True
        
        return False
