import re
import sys
import argparse\nimport requests
import random
from datetime import datetime

# External libraries for professional output
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from rich.text import Text

# --- Constants ---
DEVELOPER_USERNAME = "@diwazz"
BOT_NAME = "[✦] Stripe Charge Checker V2 [✦]"
CHARGE_AMOUNT = "$2.00"

# --- Mock Data and Simulation Functions ---

def mock_bin_lookup(bin_number):
    """Simulates a BIN lookup service."""
    bins = {
        "400000": {"vendor": "VISA", "type": "Credit", "level": "Classic", "country": "US", "bank": "Mock Bank 1"},
        "510000": {"vendor": "Mastercard", "type": "Debit", "level": "Standard", "country": "CA", "bank": "Mock Bank 2"},
        "370000": {"vendor": "Amex", "type": "Credit", "level": "Gold", "country": "GB", "bank": "Mock Bank 3"},
    }
    
    # Use the first 6 digits for a mock lookup
    for prefix, details in bins.items():
        if bin_number.startswith(prefix):
            return details
    
    return {"vendor": "Unknown", "type": "Unknown", "level": "Unknown", "country": "Unknown", "bank": "Unknown"}

def simulate_stripe_charge(card_data, bin_details):
    """
    Simulates a Stripe $2 charge attempt.
    
    NOTE: This is a simulation. In a real application, this function would
    make a secure API call to a server-side Stripe endpoint.
    """
    
    # Simple simulation logic based on card number (for demonstration)
    last_digit = int(card_data['cc'][-1])
    
    if last_digit % 2 == 0:
        # Even last digit -> Approved (Simulated)
        status = "Approved"
        reason = "Payment successfully processed."
    else:
        # Odd last digit -> Declined (Simulated)
        status = "Declined"
        
        # Randomly select a decline reason for professionalism
        decline_reasons = [
            "Insufficient funds.",
            "Card declined by issuer.",
            "Transaction not permitted.",
            "Expired card.",
            "Security code invalid."
        ]
        reason = random.choice(decline_reasons)
        
    return {"status": status, "reason": reason, "charge_id": f"ch_{random.randint(1000000, 9999999)}"}

# --- Core Logic ---

def parse_card_data(card_string):
    """Parses the cc|mm|yy|cvv string into a dictionary."""
    parts = card_string.split('|')
    if len(parts) != 4:
        raise ValueError("Invalid format. Must be cc|mm|yy|cvv.")
    
    cc, mm, yy, cvv = [p.strip() for p in parts]
    
    # Basic validation
    if not re.match(r'^\d{12,19}$', cc):
        raise ValueError("Invalid card number (must be 12-19 digits).")
    if not re.match(r'^\d{1,2}$', mm) or not (1 <= int(mm) <= 12):
        raise ValueError("Invalid month (MM).")
    if not re.match(r'^\d{2}$', yy):
        raise ValueError("Invalid year (YY).")
    if not re.match(r'^\d{3,4}$', cvv):
        raise ValueError("Invalid CVV (must be 3 or 4 digits).")

    # Convert 2-digit year to 4-digit year (assuming 2000s)
    current_year = datetime.now().year % 100
    full_year = int(yy)
    if full_year < current_year:
        full_year += 2000
    elif full_year < 70: # Assume 2070 is the cutoff for 1900s vs 2000s
        full_year += 2000
    else:
        full_year += 1900

    return {
        "cc": cc,
        "mm": mm,
        "yy": str(full_year),
        "cvv": cvv,
        "bin": cc[:6]
    }

def cli():
    console = Console()
    
    parser = argparse.ArgumentParser(
        description=f"{BOT_NAME} - Simulates a Stripe $2 charge check.",
        epilog=f"Developer: {DEVELOPER_USERNAME}"
    )
    parser.add_argument(
        'card_details', 
        type=str, 
        help='Card details in the format: cc|mm|yy|cvv (e.g., 4000000000000000|12|25|123)'
    )
    
    args = parser.parse_args()
    
    console.print(Panel(
        Text(f"{BOT_NAME}\nCharge Amount: {CHARGE_AMOUNT}", justify="center", style="bold cyan"),
        border_style="cyan"
    ))
    
    try:
        # 1. Parse Card Data
        card_data = parse_card_data(args.card_details)
        console.print(f"[bold yellow]→ Parsing Card Data...[/bold yellow]")
        
        # 2. BIN Lookup
        bin_details = mock_bin_lookup(card_data['bin'])
        console.print(f"[bold yellow]→ Performing BIN Lookup...[/bold yellow]")
        
        # 3. Simulate Charge
        charge_result = simulate_stripe_charge(card_data, bin_details)
        
        # 4. Display Results
        
        # Determine status style
        is_approved = charge_result['status'] == "Approved"
        status_style = "bold white on green" if is_approved else "bold white on red"
        status_text = Text(charge_result['status'], style=status_style)
        
        # Create BIN Details Table
        bin_table = Table(title="BIN Details", show_header=False, header_style="bold magenta")
        bin_table.add_column("Key", style="dim")
        bin_table.add_column("Value", style="bold")
        
        bin_table.add_row("BIN", card_data['bin'])
        bin_table.add_row("Vendor", bin_details['vendor'])
        bin_table.add_row("Type", bin_details['type'])
        bin_table.add_row("Level", bin_details['level'])
        bin_table.add_row("Country", bin_details['country'])
        bin_table.add_row("Bank", bin_details['bank'])
        
        # Create Charge Result Table
        result_table = Table(title="Charge Result", show_header=False, header_style="bold magenta")
        result_table.add_column("Key", style="dim")
        result_table.add_column("Value", style="bold")
        
        result_table.add_row("Amount", CHARGE_AMOUNT)
        result_table.add_row("Card", f"{card_data['cc'][:4]}XXXXXXXX{card_data['cc'][-4:]}")
        result_table.add_row("Expiry", f"{card_data['mm']}/{card_data['yy']}")
        result_table.add_row("Status", status_text)
        result_table.add_row("Reason", charge_result['reason'])
        result_table.add_row("Charge ID", charge_result['charge_id'])
        
        # Final Panel Output
        console.print(Panel(
            bin_table, 
            title="[bold magenta]BIN Information[/bold magenta]", 
            border_style="magenta"
        ))
        
        console.print(Panel(
            result_table, 
            title=f"[bold {'green' if is_approved else 'red'}]Charge Status: {charge_result['status']}[/bold {'green' if is_approved else 'red'}]", 
            border_style="green" if is_approved else "red"
        ))
        
    except ValueError as e:
        console.print(Panel(
            Text(f"Input Error: {e}", style="bold white on red"),
            title="[bold red]ERROR[/bold red]",
            border_style="red"
        ))
    except Exception as e:
        console.print(Panel(
            Text(f"An unexpected error occurred: {e}", style="bold white on red"),
            title="[bold red]FATAL ERROR[/bold red]",
            border_style="red"
        ))

