#!/usr/bin/env python3
"""
Test Instagram login fix
"""

import os
from pathlib import Path
from dotenv import load_dotenv
import instaloader

load_dotenv()

username = os.getenv('INSTAGRAM_USERNAME')
password = os.getenv('INSTAGRAM_PASSWORD')
target = os.getenv('INSTAGRAM_TARGET')

print(f"Username: {username}")
print(f"Target: {target}")

# Create a simple instaloader instance
L = instaloader.Instaloader()

# Session file
session_file = Path('test_data/.sessions') / f'{username}.session'
session_file.parent.mkdir(parents=True, exist_ok=True)

print(f"\nSession file: {session_file}")
print(f"Session exists: {session_file.exists()}")

# Try different approaches
print("\n" + "="*50)
print("Testing login approaches:")
print("="*50)

# Method 1: Direct login
print("\n1. Testing direct login...")
try:
    L.login(username, password)
    print("✅ Direct login succeeded")
    
    # Save session
    L.save_session_to_file(str(session_file))
    print(f"✅ Session saved to {session_file}")
    
except Exception as e:
    print(f"❌ Direct login failed: {e}")

# Method 2: Load session if it exists
print("\n2. Testing session loading...")
L2 = instaloader.Instaloader()
try:
    if session_file.exists():
        # The correct way to load a session
        L2.load_session_from_file(username, str(session_file))
        print("✅ Session loaded successfully")
    else:
        print("No session file to load")
except Exception as e:
    print(f"❌ Session loading failed: {e}")

# Method 3: Test fetching a post
print("\n3. Testing post fetch...")
try:
    profile = instaloader.Profile.from_username(L.context, target)
    print(f"✅ Got profile: @{profile.username}")
    print(f"   Full name: {profile.full_name}")
    print(f"   Posts: {profile.mediacount}")
    print(f"   Followers: {profile.followers}")
    
    # Get first post
    posts = profile.get_posts()
    for i, post in enumerate(posts):
        if i >= 1:
            break
        print(f"\n   First post:")
        print(f"   - Date: {post.date_utc}")
        print(f"   - Likes: {post.likes}")
        print(f"   - Caption: {post.caption[:50] if post.caption else 'No caption'}...")
        
except Exception as e:
    print(f"❌ Profile fetch failed: {e}")
    import traceback
    traceback.print_exc()