from flask import Blueprint, request, jsonify
import random
import time
from datetime import datetime

services_bp = Blueprint('services', __name__)

# Mock data for testing
MOCK_NIN_DATA = {
    "12345678901": {
        "firstname": "John",
        "lastname": "Doe", 
        "middlename": "Smith",
        "phone": "08012345678",
        "email": "john.doe@email.com",
        "gender": "Male",
        "birthdate": "1990-01-15",
        "birthstate": "Lagos",
        "birthcountry": "Nigeria",
        "residence_state": "Lagos",
        "residence_lga": "Ikeja"
    }
}

MOCK_BVN_DATA = {
    "12345678901": {
        "firstname": "John",
        "lastname": "Doe",
        "middlename": "Smith", 
        "phone": "08012345678",
        "email": "john.doe@email.com",
        "gender": "Male",
        "date_of_birth": "15-Jan-1990",
        "registration_date": "01-Jan-2015"
    }
}

NETWORK_PLANS = {
    "mtn": {
        "data": [
            {"code": "mtn_1gb", "name": "1GB - 30 Days", "price": 280},
            {"code": "mtn_2gb", "name": "2GB - 30 Days", "price": 560},
            {"code": "mtn_5gb", "name": "5GB - 30 Days", "price": 1400},
            {"code": "mtn_10gb", "name": "10GB - 30 Days", "price": 2800}
        ],
        "airtime": {"min": 50, "max": 50000}
    },
    "glo": {
        "data": [
            {"code": "glo_1gb", "name": "1GB - 30 Days", "price": 270},
            {"code": "glo_2gb", "name": "2GB - 30 Days", "price": 540},
            {"code": "glo_5gb", "name": "5GB - 30 Days", "price": 1350},
            {"code": "glo_10gb", "name": "10GB - 30 Days", "price": 2700}
        ],
        "airtime": {"min": 50, "max": 50000}
    },
    "airtel": {
        "data": [
            {"code": "airtel_1gb", "name": "1GB - 30 Days", "price": 275},
            {"code": "airtel_2gb", "name": "2GB - 30 Days", "price": 550},
            {"code": "airtel_5gb", "name": "5GB - 30 Days", "price": 1375},
            {"code": "airtel_10gb", "name": "10GB - 30 Days", "price": 2750}
        ],
        "airtime": {"min": 50, "max": 50000}
    },
    "9mobile": {
        "data": [
            {"code": "9mobile_1gb", "name": "1GB - 30 Days", "price": 290},
            {"code": "9mobile_2gb", "name": "2GB - 30 Days", "price": 580},
            {"code": "9mobile_5gb", "name": "5GB - 30 Days", "price": 1450},
            {"code": "9mobile_10gb", "name": "10GB - 30 Days", "price": 2900}
        ],
        "airtime": {"min": 50, "max": 50000}
    }
}

CABLE_TV_PACKAGES = {
    "dstv": [
        {"code": "dstv_padi", "name": "DStv Padi", "price": 2950},
        {"code": "dstv_yanga", "name": "DStv Yanga", "price": 4200},
        {"code": "dstv_confam", "name": "DStv Confam", "price": 7400},
        {"code": "dstv_compact", "name": "DStv Compact", "price": 10500},
        {"code": "dstv_premium", "name": "DStv Premium", "price": 24500}
    ],
    "gotv": [
        {"code": "gotv_smallie", "name": "GOtv Smallie", "price": 1575},
        {"code": "gotv_jinja", "name": "GOtv Jinja", "price": 2700},
        {"code": "gotv_jolli", "name": "GOtv Jolli", "price": 3950},
        {"code": "gotv_max", "name": "GOtv Max", "price": 5700}
    ],
    "startimes": [
        {"code": "startimes_nova", "name": "Startimes Nova", "price": 1200},
        {"code": "startimes_basic", "name": "Startimes Basic", "price": 2200},
        {"code": "startimes_smart", "name": "Startimes Smart", "price": 2800},
        {"code": "startimes_classic", "name": "Startimes Classic", "price": 3300}
    ]
}

# Identity Verification Routes

@services_bp.route('/verify/nin', methods=['POST'])
def verify_nin():
    """Verify National Identification Number"""
    try:
        data = request.get_json()
        nin = data.get('nin')
        
        if not nin or len(nin) != 11:
            return jsonify({
                'status': 'error',
                'message': 'Invalid NIN format. NIN must be 11 digits'
            }), 400
        
        # Simulate API processing time
        time.sleep(2)
        
        # Mock verification
        if nin in MOCK_NIN_DATA:
            return jsonify({
                'status': 'success',
                'verified': True,
                'data': MOCK_NIN_DATA[nin],
                'transaction_id': f'NIN_{int(time.time())}_{random.randint(1000, 9999)}'
            })
        else:
            # Generate mock data for demo
            return jsonify({
                'status': 'success',
                'verified': True,
                'data': {
                    'firstname': 'Demo',
                    'lastname': 'User',
                    'middlename': 'Test',
                    'phone': f'080{random.randint(10000000, 99999999)}',
                    'gender': random.choice(['Male', 'Female']),
                    'birthdate': '1990-01-01',
                    'birthstate': 'Lagos',
                    'residence_state': 'Lagos'
                },
                'transaction_id': f'NIN_{int(time.time())}_{random.randint(1000, 9999)}'
            })
    
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': 'Verification failed. Please try again.'
        }), 500

@services_bp.route('/verify/bvn', methods=['POST'])
def verify_bvn():
    """Verify Bank Verification Number"""
    try:
        data = request.get_json()
        bvn = data.get('bvn')
        
        if not bvn or len(bvn) != 11:
            return jsonify({
                'status': 'error',
                'message': 'Invalid BVN format. BVN must be 11 digits'
            }), 400
        
        # Simulate API processing time
        time.sleep(2)
        
        # Mock verification
        if bvn in MOCK_BVN_DATA:
            return jsonify({
                'status': 'success',
                'verified': True,
                'data': MOCK_BVN_DATA[bvn],
                'transaction_id': f'BVN_{int(time.time())}_{random.randint(1000, 9999)}'
            })
        else:
            # Generate mock data for demo
            return jsonify({
                'status': 'success',
                'verified': True,
                'data': {
                    'firstname': 'Demo',
                    'lastname': 'User',
                    'middlename': 'Test',
                    'phone': f'080{random.randint(10000000, 99999999)}',
                    'gender': random.choice(['Male', 'Female']),
                    'date_of_birth': '01-Jan-1990',
                    'registration_date': '01-Jan-2015'
                },
                'transaction_id': f'BVN_{int(time.time())}_{random.randint(1000, 9999)}'
            })
    
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': 'Verification failed. Please try again.'
        }), 500

# Mobile Services Routes

@services_bp.route('/mobile/networks', methods=['GET'])
def get_networks():
    """Get available mobile networks"""
    return jsonify({
        'status': 'success',
        'networks': [
            {'code': 'mtn', 'name': 'MTN Nigeria', 'logo': '/assets/mtn-logo.png'},
            {'code': 'glo', 'name': 'Globacom', 'logo': '/assets/glo-logo.png'},
            {'code': 'airtel', 'name': 'Airtel Nigeria', 'logo': '/assets/airtel-logo.png'},
            {'code': '9mobile', 'name': '9mobile', 'logo': '/assets/9mobile-logo.png'}
        ]
    })

@services_bp.route('/mobile/data-plans/<network>', methods=['GET'])
def get_data_plans(network):
    """Get data plans for a specific network"""
    if network not in NETWORK_PLANS:
        return jsonify({
            'status': 'error',
            'message': 'Network not supported'
        }), 400
    
    return jsonify({
        'status': 'success',
        'network': network,
        'plans': NETWORK_PLANS[network]['data']
    })

@services_bp.route('/mobile/buy-data', methods=['POST'])
def buy_data():
    """Purchase data bundle"""
    try:
        data = request.get_json()
        network = data.get('network')
        plan_code = data.get('plan_code')
        phone = data.get('phone')
        
        if not all([network, plan_code, phone]):
            return jsonify({
                'status': 'error',
                'message': 'Missing required fields: network, plan_code, phone'
            }), 400
        
        if network not in NETWORK_PLANS:
            return jsonify({
                'status': 'error',
                'message': 'Network not supported'
            }), 400
        
        # Find the plan
        plan = None
        for p in NETWORK_PLANS[network]['data']:
            if p['code'] == plan_code:
                plan = p
                break
        
        if not plan:
            return jsonify({
                'status': 'error',
                'message': 'Plan not found'
            }), 400
        
        # Simulate processing time
        time.sleep(3)
        
        # Mock successful purchase
        return jsonify({
            'status': 'success',
            'message': 'Data purchase successful',
            'transaction_id': f'DATA_{int(time.time())}_{random.randint(1000, 9999)}',
            'details': {
                'network': network.upper(),
                'plan': plan['name'],
                'phone': phone,
                'amount': plan['price'],
                'date': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            }
        })
    
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': 'Transaction failed. Please try again.'
        }), 500

@services_bp.route('/mobile/buy-airtime', methods=['POST'])
def buy_airtime():
    """Purchase airtime"""
    try:
        data = request.get_json()
        network = data.get('network')
        amount = data.get('amount')
        phone = data.get('phone')
        
        if not all([network, amount, phone]):
            return jsonify({
                'status': 'error',
                'message': 'Missing required fields: network, amount, phone'
            }), 400
        
        if network not in NETWORK_PLANS:
            return jsonify({
                'status': 'error',
                'message': 'Network not supported'
            }), 400
        
        amount = float(amount)
        min_amount = NETWORK_PLANS[network]['airtime']['min']
        max_amount = NETWORK_PLANS[network]['airtime']['max']
        
        if amount < min_amount or amount > max_amount:
            return jsonify({
                'status': 'error',
                'message': f'Amount must be between ₦{min_amount} and ₦{max_amount}'
            }), 400
        
        # Simulate processing time
        time.sleep(2)
        
        # Mock successful purchase
        return jsonify({
            'status': 'success',
            'message': 'Airtime purchase successful',
            'transaction_id': f'AIRTIME_{int(time.time())}_{random.randint(1000, 9999)}',
            'details': {
                'network': network.upper(),
                'phone': phone,
                'amount': amount,
                'date': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            }
        })
    
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': 'Transaction failed. Please try again.'
        }), 500

# Cable TV Routes

@services_bp.route('/cable/providers', methods=['GET'])
def get_cable_providers():
    """Get available cable TV providers"""
    return jsonify({
        'status': 'success',
        'providers': [
            {'code': 'dstv', 'name': 'DStv', 'logo': '/assets/dstv-logo.png'},
            {'code': 'gotv', 'name': 'GOtv', 'logo': '/assets/gotv-logo.png'},
            {'code': 'startimes', 'name': 'Startimes', 'logo': '/assets/startimes-logo.png'}
        ]
    })

@services_bp.route('/cable/packages/<provider>', methods=['GET'])
def get_cable_packages(provider):
    """Get packages for a specific cable TV provider"""
    if provider not in CABLE_TV_PACKAGES:
        return jsonify({
            'status': 'error',
            'message': 'Provider not supported'
        }), 400
    
    return jsonify({
        'status': 'success',
        'provider': provider,
        'packages': CABLE_TV_PACKAGES[provider]
    })

@services_bp.route('/cable/subscribe', methods=['POST'])
def subscribe_cable():
    """Subscribe to cable TV package"""
    try:
        data = request.get_json()
        provider = data.get('provider')
        package_code = data.get('package_code')
        smartcard_number = data.get('smartcard_number')
        
        if not all([provider, package_code, smartcard_number]):
            return jsonify({
                'status': 'error',
                'message': 'Missing required fields: provider, package_code, smartcard_number'
            }), 400
        
        if provider not in CABLE_TV_PACKAGES:
            return jsonify({
                'status': 'error',
                'message': 'Provider not supported'
            }), 400
        
        # Find the package
        package = None
        for p in CABLE_TV_PACKAGES[provider]:
            if p['code'] == package_code:
                package = p
                break
        
        if not package:
            return jsonify({
                'status': 'error',
                'message': 'Package not found'
            }), 400
        
        # Simulate processing time
        time.sleep(3)
        
        # Mock successful subscription
        return jsonify({
            'status': 'success',
            'message': 'Cable TV subscription successful',
            'transaction_id': f'CABLE_{int(time.time())}_{random.randint(1000, 9999)}',
            'details': {
                'provider': provider.upper(),
                'package': package['name'],
                'smartcard_number': smartcard_number,
                'amount': package['price'],
                'date': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                'expiry_date': '2024-09-03'  # Mock expiry date
            }
        })
    
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': 'Subscription failed. Please try again.'
        }), 500

# Business Services Routes

@services_bp.route('/business/cac/search', methods=['POST'])
def search_cac():
    """Search for company information"""
    try:
        data = request.get_json()
        company_name = data.get('company_name')
        rc_number = data.get('rc_number')
        
        if not company_name and not rc_number:
            return jsonify({
                'status': 'error',
                'message': 'Either company_name or rc_number is required'
            }), 400
        
        # Simulate processing time
        time.sleep(2)
        
        # Mock company data
        return jsonify({
            'status': 'success',
            'data': {
                'company_name': company_name or 'Demo Company Limited',
                'rc_number': rc_number or f'RC{random.randint(100000, 999999)}',
                'registration_date': '2020-01-15',
                'company_type': 'Private Limited Company',
                'status': 'Active',
                'address': 'Lagos, Nigeria',
                'directors': [
                    {'name': 'John Doe', 'position': 'Managing Director'},
                    {'name': 'Jane Smith', 'position': 'Director'}
                ]
            },
            'transaction_id': f'CAC_{int(time.time())}_{random.randint(1000, 9999)}'
        })
    
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': 'Search failed. Please try again.'
        }), 500

# Educational Services Routes

@services_bp.route('/education/jamb/profile', methods=['POST'])
def create_jamb_profile():
    """Create JAMB profile code"""
    try:
        data = request.get_json()
        email = data.get('email')
        phone = data.get('phone')
        
        if not all([email, phone]):
            return jsonify({
                'status': 'error',
                'message': 'Email and phone are required'
            }), 400
        
        # Simulate processing time
        time.sleep(3)
        
        # Mock profile creation
        profile_code = f'{random.randint(10000000, 99999999)}{random.choice("ABCDEFGHIJKLMNOPQRSTUVWXYZ")}{random.choice("ABCDEFGHIJKLMNOPQRSTUVWXYZ")}'
        
        return jsonify({
            'status': 'success',
            'message': 'JAMB profile code created successfully',
            'data': {
                'profile_code': profile_code,
                'email': email,
                'phone': phone,
                'created_date': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            },
            'transaction_id': f'JAMB_{int(time.time())}_{random.randint(1000, 9999)}'
        })
    
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': 'Profile creation failed. Please try again.'
        }), 500

# Utility Routes

@services_bp.route('/wallet/balance', methods=['GET'])
def get_wallet_balance():
    """Get user wallet balance (mock)"""
    return jsonify({
        'status': 'success',
        'balance': random.randint(1000, 50000),
        'currency': 'NGN'
    })

@services_bp.route('/transactions/history', methods=['GET'])
def get_transaction_history():
    """Get transaction history (mock)"""
    transactions = []
    for i in range(10):
        transactions.append({
            'id': f'TXN_{int(time.time())}_{random.randint(1000, 9999)}',
            'type': random.choice(['NIN Verification', 'Data Purchase', 'Airtime', 'Cable TV']),
            'amount': random.randint(100, 5000),
            'status': random.choice(['Success', 'Pending', 'Failed']),
            'date': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        })
    
    return jsonify({
        'status': 'success',
        'transactions': transactions
    })

@services_bp.route('/contact', methods=['POST'])
def contact_form():
    """Handle contact form submission"""
    try:
        data = request.get_json()
        name = data.get('name')
        email = data.get('email')
        phone = data.get('phone')
        message = data.get('message')
        
        if not all([name, email, message]):
            return jsonify({
                'status': 'error',
                'message': 'Name, email, and message are required'
            }), 400
        
        # In a real application, you would save this to database or send email
        return jsonify({
            'status': 'success',
            'message': 'Thank you for your message. We will get back to you within 24 hours.'
        })
    
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': 'Failed to send message. Please try again.'
        }), 500

