#!/usr/bin/env python3
import psycopg2
from psycopg2.extras import RealDictCursor

# Get connection from .env
with open('.env') as f:
    for line in f:
        if line.startswith('DATABASE_URL'):
            db_url = line.split('=', 1)[1].strip()
            break

# Parse URL
parts = db_url.replace('postgresql://', '').split('@')
user_pass = parts[0].split(':')
host_port_db = parts[1].split('/')

conn = psycopg2.connect(
    host='localhost',
    port=5433,
    database=host_port_db[1],
    user=user_pass[0],
    password=user_pass[1]
)

cursor = conn.cursor(cursor_factory=RealDictCursor)

# Check customer 17
print("=== CUSTOMER 17 (Blåhund Import) ===")
cursor.execute("SELECT * FROM customers WHERE id = 17")
customer = cursor.fetchone()
print(f"Customer: {customer}")

print("\n=== CONTACT_COMPANIES for customer 17 ===")
cursor.execute("SELECT * FROM contact_companies WHERE customer_id = 17")
cc_rows = cursor.fetchall()
print(f"Found {len(cc_rows)} contact_companies entries:")
for row in cc_rows:
    print(f"  - Contact ID: {row['contact_id']}, Primary: {row.get('is_primary')}")

if cc_rows:
    contact_ids = [r['contact_id'] for r in cc_rows]
    placeholders = ','.join(['%s'] * len(contact_ids))
    cursor.execute(f"SELECT id, first_name, last_name FROM contacts WHERE id IN ({placeholders})", contact_ids)
    contacts = cursor.fetchall()
    print(f"\n=== CONTACTS ===")
    for c in contacts:
        print(f"  ID: {c['id']}, Name: {c.get('first_name')} {c.get('last_name')}")

conn.close()
