"""Debug script to test validation"""
import os
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.test import Client
from django.contrib.auth import get_user_model
from django.urls import reverse
from datetime import date
from accounting.models import Account, FiscalPeriod
from users.models import Branch

User = get_user_model()

# Create test data
print("Creating test data...")
user = User.objects.create_user(
    username='testuser',
    password='testpass123',
    is_staff=True
)

branch = Branch.objects.create(
    name='Test Branch',
    location='Test Location'
)

cash_account = Account.objects.create(
    code='101001',
    name='Cash',
    account_type='asset',
    description='Cash account'
)

loan_account = Account.objects.create(
    code='202001',
    name='Loan Portfolio',
    account_type='asset',
    description='Loan portfolio'
)

# Create closed period
today = date.today()
period = FiscalPeriod.objects.create(
    name=f'Closed Period {today.year}',
    period_type='monthly',
    start_date=date(today.year, today.month, 1),
    end_date=date(today.year, today.month, 28),
    status='closed'
)

print(f"Created closed period: {period}")

# Make request
client = Client()
client.login(username='testuser', password='testpass123')

url = reverse('accounting:journal_entry_create')
data = {
    'transaction_date': today,
    'description': 'Entry in closed period',
    'branch': branch.id,
    
    # Formset management form
    'lines-TOTAL_FORMS': '2',
    'lines-INITIAL_FORMS': '0',
    'lines-MIN_NUM_FORMS': '2',
    'lines-MAX_NUM_FORMS': '1000',
    
    # Line 1 - Debit
    'lines-0-account': cash_account.id,
    'lines-0-description': 'Debit cash',
    'lines-0-debit_amount': '1000.00',
    'lines-0-credit_amount': '0.00',
    
    # Line 2 - Credit
    'lines-1-account': loan_account.id,
    'lines-1-description': 'Credit loan',
    'lines-1-debit_amount': '0.00',
    'lines-1-credit_amount': '1000.00',
}

print("\nMaking POST request...")
response = client.post(url, data)

print(f"Response status: {response.status_code}")
print(f"\nMessages in context:")
if 'messages' in response.context:
    messages = list(response.context['messages'])
    for m in messages:
        print(f"  - {m}")
else:
    print("  No messages in context")

# Check database
from accounting.models import JournalEntry
entry = JournalEntry.objects.filter(description='Entry in closed period').first()
print(f"\nEntry created: {entry}")

# Cleanup
print("\nCleaning up...")
User.objects.all().delete()
Branch.objects.all().delete()
Account.objects.all().delete()
FiscalPeriod.objects.all().delete()
print("Done!")
