import os
import uuid
import tigerbeetle as tb
from django.contrib.auth import get_user_model
from django.conf import settings
from billing_app.models import Account as AccountModel
from billing_app.tigerbeetle_client import tigerbeetle_client

# Ensure Django settings are configured if not already
if not settings.configured:
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'billing.settings')
    import django
    django.setup()

# Define Ledger and Code (these are example values, adjust as needed)
LEDGER = 700
CODE = 10

print("--- Starting Raw Data Display for Multiple Transactions ---")

# 1. Create source, destination, and bank accounts
print("Creating source, destination, and bank accounts...")
source_account_id = uuid.uuid4()
destination_account_id = uuid.uuid4()
bank_account_id = uuid.uuid4() # Bank account for initial funding

# Create in local DB
source_local_account = AccountModel.objects.create(uuid=source_account_id)
destination_local_account = AccountModel.objects.create(uuid=destination_account_id)
bank_local_account = AccountModel.objects.create(uuid=bank_account_id)

# Prepare for TigerBeetle
accounts_to_create_details = [
    {
        "id": source_account_id.int,
        "ledger": LEDGER,
        "code": CODE,
        "flags": tb.AccountFlags.NONE # All flags set to NONE for simplicity
    },
    {
        "id": destination_account_id.int,
        "ledger": LEDGER,
        "code": CODE,
        "flags": tb.AccountFlags.NONE # All flags set to NONE for simplicity
    },
    {
        "id": bank_account_id.int,
        "ledger": LEDGER,
        "code": CODE,
        "flags": tb.AccountFlags.NONE # Changed: Removed CREDIT_RESERVED, set to NONE
    },
]

# Create accounts in TigerBeetle using create_account (singular) for each
account_creation_results = []
for acc_details in accounts_to_create_details:
    flags = acc_details.get("flags", tb.AccountFlags.NONE)
    results = tigerbeetle_client.create_account(
        acc_details["id"],
        acc_details["ledger"],
        acc_details["code"],
        flags
    )
    if results: # If non-empty, it means there are errors
        account_creation_results.extend(results)

if account_creation_results:
    print(f"Failed to create accounts in TigerBeetle. Raw results: {account_creation_results}") # Print raw results
    import sys
    sys.exit(1)
else:
    print(f"Source account created: {source_account_id}")
    print(f"Destination account created: {destination_account_id}")
    print(f"Bank account created: {bank_account_id}")

# Store all transfer IDs for later lookup
all_transfer_ids = []

# 2. Fund the source account (initial balance)
print("Funding source account with initial balance...")
initial_fund_id = uuid.uuid4()
initial_fund_transfer = tb.Transfer(
    id=initial_fund_id.int,
    debit_account_id=bank_account_id.int, # Use real bank account ID
    credit_account_id=source_account_id.int,
    amount=1000, # Initial amount
    ledger=LEDGER,
    code=CODE,
)
fund_results = tigerbeetle_client.create_transfer(
    initial_fund_transfer.id,
    initial_fund_transfer.debit_account_id,
    initial_fund_transfer.credit_account_id,
    initial_fund_transfer.amount,
    initial_fund_transfer.ledger,
    initial_fund_transfer.code,
    initial_fund_transfer.flags
)
if fund_results: # If non-empty, it means there are errors
    print(f"Failed to fund source account. Raw results: {fund_results}")
    import sys
    sys.exit(1)
else:
    print(f"Source account funded with 1000. Transfer ID: {initial_fund_id}")
    all_transfer_ids.append(initial_fund_id.int) # Store ID

# 3. Perform 5 transactions from source to destination
print("Performing 5 transactions from source to destination...")
for i in range(1, 6):
    transfer_id = uuid.uuid4()
    transfer_amount = 100 # Example amount for each transfer

    transfer = tb.Transfer( # tb.Transfer object
        id=transfer_id.int,
        debit_account_id=source_account_id.int,
        credit_account_id=destination_account_id.int,
        amount=transfer_amount,
        ledger=LEDGER,
        code=CODE,
    )
    transfer_results = tigerbeetle_client.create_transfer(
        transfer.id,
        transfer.debit_account_id,
        transfer.credit_account_id,
        transfer.amount,
        transfer.ledger,
        transfer.code,
        transfer.flags
    )
    if transfer_results:
        print(f"Transaction {i} failed. Raw results: {transfer_results}")
    else:
        print(f"Transaction {i} (Amount: {transfer_amount}) completed. Transfer ID: {transfer.id}")
        all_transfer_ids.append(transfer_id.int) # Store ID

# 4. Query detailed account information from TigerBeetle
print("\n--- Raw Account Details (from TigerBeetle) ---")
account_ids_to_lookup = [source_account_id.int, destination_account_id.int, bank_account_id.int]
detailed_accounts = tigerbeetle_client.lookup_accounts(account_ids_to_lookup)

for account in detailed_accounts:
    if isinstance(account, tb.Account):
        print(f"Account ID: {uuid.UUID(int=account.id)}")
        print(f"  User Data 128: {account.user_data_128}")
        print(f"  User Data 64: {account.user_data_64}")
        print(f"  User Data 32: {account.user_data_32}")
        print(f"  Ledger: {account.ledger}")
        print(f"  Code: {account.code}")
        print(f"  Flags: {account.flags}")
        print(f"  Timestamp: {account.timestamp}")
        print(f"  Debits Posted: {account.debits_posted}")
        print(f"  Credits Posted: {account.credits_posted}")
        print(f"  Debits Pending: {account.debits_pending}")
        print(f"  Credits Pending: {account.credits_pending}")
        print(f"  Net Balance: {account.credits_posted - account.debits_posted}")
        print("-" * 30)
    else:
        print(f"Could not retrieve details for account ID: {account.id if hasattr(account, 'id') else 'Unknown'}")

# 5. Query ALL transfer information
print("\n--- Raw Transfer Details (from TigerBeetle) ---")
detailed_transfers = tigerbeetle_client._client.lookup_transfers(all_transfer_ids)

for transfer_detail in detailed_transfers:
    if isinstance(transfer_detail, tb.Transfer):
        print(f"Transfer ID: {uuid.UUID(int=transfer_detail.id)}")
        print(f"  Debit Account ID: {uuid.UUID(int=transfer_detail.debit_account_id)}")
        print(f"  Credit Account ID: {uuid.UUID(int=transfer_detail.credit_account_id)}")
        print(f"  Amount: {transfer_detail.amount}")
        print(f"  Pending ID: {transfer_detail.pending_id}")
        print(f"  User Data 128: {transfer_detail.user_data_128}")
        print(f"  User Data 64: {transfer_detail.user_data_64}")
        print(f"  User Data 32: {transfer_detail.user_data_32}")
        print(f"  Timeout: {transfer_detail.timeout}")
        print(f"  Ledger: {transfer_detail.ledger}")
        print(f"  Code: {transfer_detail.code}")
        print(f"  Flags: {transfer_detail.flags}")
        print(f"  Timestamp: {transfer_detail.timestamp}")
        print("-" * 30)
    else:
        print(f"Could not retrieve details for transfer ID: {transfer_detail.id if hasattr(transfer_detail, 'id') else 'Unknown'}")

print("\n--- Raw Data Display Complete ---")
