#!/usr/bin/env python
"""
Script to check current database state for tenancy system
DO NOT MAKE ANY CHANGES - READ ONLY
"""
import os
import sys
import django

# Set up Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'igny8_core.settings')
sys.path.insert(0, os.path.dirname(__file__))
django.setup()

from igny8_core.auth.models import Plan, Account, User, Site, Sector, Subscription
from igny8_core.business.billing.models import CreditTransaction

print("=" * 80)
print("CURRENT DATABASE STATE ANALYSIS (READ-ONLY)")
print("=" * 80)

# Check Plans
print("\n=== EXISTING PLANS ===")
plans = Plan.objects.all()
if plans.exists():
    for p in plans:
        print(f"{p.id}. [{p.slug}] {p.name}")
        print(f"   Price: ${p.price}/{p.billing_cycle}")
        print(f"   Credits: {p.included_credits} (legacy: {p.credits_per_month})")
        print(f"   Max Sites: {p.max_sites}, Max Users: {p.max_users}, Max Industries: {p.max_industries}")
        print(f"   Active: {p.is_active}")
        print(f"   Features: {p.features}")
        print()
else:
    print("No plans found in database")

print(f"Total plans: {plans.count()}\n")

# Check Accounts
print("=== EXISTING ACCOUNTS ===")
accounts = Account.objects.select_related('plan', 'owner').all()[:10]
if accounts.exists():
    for acc in accounts:
        print(f"{acc.id}. [{acc.slug}] {acc.name}")
        print(f"   Owner: {acc.owner.email if acc.owner else 'None'}")
        print(f"   Plan: {acc.plan.slug if acc.plan else 'None'}")
        print(f"   Credits: {acc.credits}")
        print(f"   Status: {acc.status}")
        print(f"   Has payment_method field: {hasattr(acc, 'payment_method')}")
        try:
            print(f"   Payment method: {acc.payment_method if hasattr(acc, 'payment_method') else 'Field does not exist'}")
        except:
            print(f"   Payment method: Field does not exist in DB")
        print()
else:
    print("No accounts found in database")

print(f"Total accounts: {Account.objects.count()}\n")

# Check Users
print("=== USER ROLES ===")
users = User.objects.select_related('account').all()[:10]
if users.exists():
    for u in users:
        print(f"{u.id}. {u.email} - Role: {u.role}")
        print(f"   Account: {u.account.slug if u.account else 'None'}")
        print(f"   Is superuser: {u.is_superuser}")
        print()
else:
    print("No users found in database")

print(f"Total users: {User.objects.count()}\n")

# Check Sites
print("=== SITES AND ACCOUNT RELATIONSHIP ===")
sites = Site.objects.select_related('account', 'industry').all()[:10]
if sites.exists():
    for site in sites:
        print(f"{site.id}. [{site.slug}] {site.name}")
        print(f"   Account: {site.account.slug if site.account else 'None'}")
        print(f"   Industry: {site.industry.name if site.industry else 'None'}")
        print(f"   Active: {site.is_active}, Status: {site.status}")
        print(f"   Sectors: {site.sectors.filter(is_active=True).count()}")
        print()
else:
    print("No sites found in database")

print(f"Total sites: {Site.objects.count()}\n")

# Check Subscriptions
print("=== SUBSCRIPTIONS ===")
subscriptions = Subscription.objects.select_related('account').all()
if subscriptions.exists():
    for sub in subscriptions:
        print(f"{sub.id}. Account: {sub.account.slug}")
        print(f"   Stripe ID: {sub.stripe_subscription_id}")
        print(f"   Status: {sub.status}")
        print(f"   Period: {sub.current_period_start} to {sub.current_period_end}")
        print(f"   Has payment_method field: {hasattr(sub, 'payment_method')}")
        try:
            print(f"   Payment method: {sub.payment_method if hasattr(sub, 'payment_method') else 'Field does not exist'}")
            print(f"   External payment ID: {sub.external_payment_id if hasattr(sub, 'external_payment_id') else 'Field does not exist'}")
        except:
            print(f"   Payment method fields: Do not exist in DB")
        print()
else:
    print("No subscriptions found in database")

print(f"Total subscriptions: {Subscription.objects.count()}\n")

# Check Credit Transactions
print("=== CREDIT TRANSACTIONS (Sample) ===")
transactions = CreditTransaction.objects.select_related('account').order_by('-created_at')[:5]
if transactions.exists():
    for tx in transactions:
        print(f"{tx.id}. Account: {tx.account.slug}")
        print(f"   Type: {tx.transaction_type}, Amount: {tx.amount}")
        print(f"   Balance after: {tx.balance_after}")
        print(f"   Description: {tx.description}")
        print(f"   Created: {tx.created_at}")
        print()
else:
    print("No credit transactions found")

print(f"Total credit transactions: {CreditTransaction.objects.count()}\n")

# Model Field Analysis
print("=== MODEL FIELD ANALYSIS ===")
print("\nAccount Model Fields:")
for field in Account._meta.get_fields():
    if not field.many_to_many and not field.one_to_many:
        print(f"  - {field.name}: {field.get_internal_type()}")

print("\nSubscription Model Fields:")
for field in Subscription._meta.get_fields():
    if not field.many_to_many and not field.one_to_many:
        print(f"  - {field.name}: {field.get_internal_type()}")

print("\nSite Model Fields:")
for field in Site._meta.get_fields():
    if not field.many_to_many and not field.one_to_many:
        field_name = field.name
        field_type = field.get_internal_type()
        if field_name in ['account', 'industry']:
            print(f"  - {field_name}: {field_type} (RELATIONSHIP)")

print("\n" + "=" * 80)
print("END OF ANALYSIS")
print("=" * 80)