from app.db import get_db_connection
from app.schemas import ProfileCreate, ProfileUpdate, ProfileResponse, DiscoverResponse
import json

class ProfileService:
    """Handle user profiles"""
    
    @staticmethod
    def create_profile(user_id: int, profile_data: ProfileCreate) -> ProfileResponse:
        """Create or update profile"""
        with get_db_connection() as conn:
            cur = conn.cursor()
            cur.execute("SELECT id FROM profiles WHERE user_id = %s", (user_id,))
            existing = cur.fetchone()
            
            interests_json = json.dumps(profile_data.interests)
            
            if existing:
                cur.execute(
                    """UPDATE profiles SET 
                       display_name = %s, age = %s, gender = %s, 
                       location = %s, bio = %s, interests = %s, updated_at = CURRENT_TIMESTAMP
                       WHERE user_id = %s""",
                    (profile_data.display_name, profile_data.age, profile_data.gender,
                     profile_data.location, profile_data.bio, interests_json, user_id)
                )
            else:
                cur.execute(
                    """INSERT INTO profiles 
                       (user_id, display_name, age, gender, location, bio, interests) 
                       VALUES (%s, %s, %s, %s, %s, %s, %s)""",
                    (user_id, profile_data.display_name, profile_data.age, profile_data.gender,
                     profile_data.location, profile_data.bio, interests_json)
                )
            conn.commit()
            
            return ProfileService.get_profile_by_user(user_id)
    
    @staticmethod
    def get_profile_by_user(user_id: int) -> ProfileResponse:
        """Get profile by user ID"""
        with get_db_connection() as conn:
            cur = conn.cursor()
            cur.execute(
                "SELECT id, user_id, display_name, age, gender, location, bio, interests FROM profiles WHERE user_id = %s",
                (user_id,)
            )
            row = cur.fetchone()
            if not row:
                return None
            
            profile_id = row[0]
            # PostgreSQL JSONB returns as list/dict, not string
            interests = row[7] if isinstance(row[7], list) else (json.loads(row[7]) if row[7] else [])
            
            # Fetch photos
            cur.execute("SELECT id, file_path FROM photos WHERE profile_id = %s ORDER BY display_order", (profile_id,))
            photos = [{"id": p[0], "file_path": p[1]} for p in cur.fetchall()]
            
            return ProfileResponse(
                id=profile_id,
                user_id=row[1],
                display_name=row[2],
                age=row[3],
                gender=row[4],
                location=row[5],
                bio=row[6],
                interests=interests,
                photos=photos
            )
    
    @staticmethod
    def discover_profiles(current_user_id: int, limit: int = 20) -> list:
        """Get profiles to discover (exclude self and basic filtering)"""
        with get_db_connection() as conn:
            cur = conn.cursor()
            cur.execute(
                """SELECT p.id, p.user_id, p.display_name, p.age, p.gender, p.location, p.bio, p.interests
                   FROM profiles p
                   WHERE p.user_id != %s
                   ORDER BY p.created_at DESC
                   LIMIT %s""",
                (current_user_id, limit)
            )
            
            profiles = []
            for row in cur.fetchall():
                profile_id = row[0]
                # PostgreSQL JSONB returns as list/dict, not string
                interests = row[7] if isinstance(row[7], list) else (json.loads(row[7]) if row[7] else [])
                
                # Fetch photos
                cur.execute(
                    "SELECT id, file_path FROM photos WHERE profile_id = %s ORDER BY display_order",
                    (profile_id,)
                )
                photos = [{"id": p[0], "file_path": p[1]} for p in cur.fetchall()]
                
                profiles.append(DiscoverResponse(
                    id=profile_id,
                    display_name=row[2],
                    age=row[3],
                    gender=row[4],
                    location=row[5],
                    bio=row[6],
                    interests=interests,
                    photos=photos
                ))
            
            return profiles
