import asyncio
import os
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy import text
from datetime import datetime

async def test_insert():
    engine = create_async_engine(os.getenv('DATABASE_URL'))
    try:
        async with engine.connect() as conn:
            print("1. Testing direct INSERT into policies table...")

            # Insert a policy directly
            await conn.execute(text("""
                INSERT INTO policy_service.policies (
                    policy_number,
                    customer_id,
                    organization_id,
                    product_type,
                    status,
                    effective_date,
                    expiration_date,
                    premium_amount,
                    currency,
                    billing_frequency,
                    coverage_details,
                    underwriting_data,
                    tags,
                    metadata_,
                    created_at,
                    updated_at,
                    created_by,
                    updated_by,
                    version
                ) VALUES (
                    'POL-2025-999999',
                    'cus_01JEMN4XZ8Y6Q3KPVWRST2FGHA',
                    'test-org-001',
                    'health',
                    'active',
                    '2025-12-03 00:00:00+00',
                    '2026-12-03 00:00:00+00',
                    500.00,
                    'USD',
                    'monthly',
                    '{}',
                    '{}',
                    ARRAY['health', 'test'],
                    '{}',
                    CURRENT_TIMESTAMP,
                    CURRENT_TIMESTAMP,
                    'test-admin-user',
                    'test-admin-user',
                    1
                )
            """))

            await conn.commit()
            print("✅ Direct INSERT successful!")

            # Query it back
            result = await conn.execute(text("""
                SELECT id, policy_number, status, premium_amount
                FROM policy_service.policies
                WHERE policy_number = 'POL-2025-999999'
            """))
            row = result.fetchone()
            if row:
                print(f"✅ Policy created: {row[0]} - {row[1]} ({row[2]}, ${row[3]})")
            else:
                print("❌ Policy not found after insert")

    except Exception as e:
        print(f"❌ Error: {type(e).__name__}: {str(e)[:200]}")
        import traceback
        traceback.print_exc()
    finally:
        await engine.dispose()

asyncio.run(test_insert())
