#!/usr/bin/env python3
"""
Focused Backend API Testing for Previously Failing Endpoints
Based on review request: Step tracking, Progress photos, Supplements log, Diet plan update, Session booking
"""

import requests
import json
import base64
from datetime import datetime, timedelta
import uuid

# Configuration
BASE_URL = "https://fitcoach-108.preview.emergentagent.com/api"
ADMIN_EMAIL = "admin@abbasfit.com"
ADMIN_PASSWORD = "admin"

class FocusedTester:
    def __init__(self):
        self.session = requests.Session()
        self.admin_token = None
        self.user_token = None
        self.test_user_id = None
        self.results = []
        
    def log_result(self, test_name, success, details="", error="", response_data=None):
        """Log test result with detailed information"""
        status = "✅ PASS" if success else "❌ FAIL"
        result = {
            "test": test_name,
            "status": status,
            "details": details,
            "error": error,
            "response_data": response_data,
            "timestamp": datetime.now().isoformat()
        }
        self.results.append(result)
        print(f"{status}: {test_name}")
        if details:
            print(f"   Details: {details}")
        if error:
            print(f"   Error: {error}")
        if response_data and not success:
            print(f"   Response: {json.dumps(response_data, indent=2)}")
        print()
    
    def setup_authentication(self):
        """Setup admin and user authentication"""
        try:
            # Admin login
            response = self.session.post(f"{BASE_URL}/auth/login", json={
                "email": ADMIN_EMAIL,
                "password": ADMIN_PASSWORD
            })
            
            if response.status_code == 200:
                data = response.json()
                self.admin_token = data.get("access_token")
                print(f"✅ Admin login successful")
                
                # Get existing user
                self.session.headers.update({"Authorization": f"Bearer {self.admin_token}"})
                users_response = self.session.get(f"{BASE_URL}/admin/users")
                
                if users_response.status_code == 200:
                    users = users_response.json()
                    if users:
                        self.test_user_id = users[0]["id"]
                        self.user_token = self.admin_token  # Use admin token for user tests
                        print(f"✅ Using existing user: {self.test_user_id}")
                        return True
                    else:
                        print("❌ No users found")
                        return False
                else:
                    print(f"❌ Failed to get users: {users_response.status_code}")
                    return False
            else:
                print(f"❌ Admin login failed: {response.status_code} - {response.text}")
                return False
                
        except Exception as e:
            print(f"❌ Setup error: {str(e)}")
            return False
    
    def test_step_tracking_detailed(self):
        """Test step tracking with detailed error analysis"""
        print("🔍 Testing Step Tracking (POST /api/user/steps)")
        
        try:
            headers = {"Authorization": f"Bearer {self.user_token}"}
            
            step_data = {
                "steps": 8500,
                "date": datetime.now().strftime("%Y-%m-%d")
            }
            
            response = self.session.post(f"{BASE_URL}/user/steps", json=step_data, headers=headers)
            
            print(f"Request URL: {BASE_URL}/user/steps")
            print(f"Request Headers: {headers}")
            print(f"Request Data: {json.dumps(step_data, indent=2)}")
            print(f"Response Status: {response.status_code}")
            print(f"Response Headers: {dict(response.headers)}")
            
            try:
                response_data = response.json()
                print(f"Response Data: {json.dumps(response_data, indent=2)}")
            except:
                print(f"Response Text: {response.text}")
                response_data = {"raw_text": response.text}
            
            if response.status_code == 200:
                if "id" in response_data and "steps" in response_data:
                    self.log_result("Step Tracking - POST", True, f"Steps logged: {response_data['steps']}")
                    return True
                else:
                    self.log_result("Step Tracking - POST", False, 
                                  error="Missing required fields in response", 
                                  response_data=response_data)
                    return False
            else:
                self.log_result("Step Tracking - POST", False, 
                              error=f"HTTP {response.status_code}", 
                              response_data=response_data)
                return False
                
        except Exception as e:
            self.log_result("Step Tracking - POST", False, error=f"Exception: {str(e)}")
            return False
    
    def test_progress_photos_detailed(self):
        """Test progress photos with detailed error analysis"""
        print("🔍 Testing Progress Photos (POST /api/user/progress-photos)")
        
        try:
            headers = {"Authorization": f"Bearer {self.user_token}"}
            
            # Create a simple base64 encoded image (1x1 pixel PNG)
            sample_image = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg=="
            
            photo_data = {
                "photo_base64": sample_image,
                "photo_type": "front",
                "week_number": 1,
                "notes": "Test progress photo"
            }
            
            response = self.session.post(f"{BASE_URL}/user/progress-photos", json=photo_data, headers=headers)
            
            print(f"Request URL: {BASE_URL}/user/progress-photos")
            print(f"Request Headers: {headers}")
            print(f"Request Data Keys: {list(photo_data.keys())}")
            print(f"Response Status: {response.status_code}")
            print(f"Response Headers: {dict(response.headers)}")
            
            try:
                response_data = response.json()
                print(f"Response Data: {json.dumps(response_data, indent=2)}")
            except:
                print(f"Response Text: {response.text}")
                response_data = {"raw_text": response.text}
            
            if response.status_code == 200:
                if "id" in response_data and "photo_type" in response_data:
                    self.log_result("Progress Photos - POST", True, f"Photo uploaded: {response_data['photo_type']}")
                    return True
                else:
                    self.log_result("Progress Photos - POST", False, 
                                  error="Missing required fields in response", 
                                  response_data=response_data)
                    return False
            else:
                self.log_result("Progress Photos - POST", False, 
                              error=f"HTTP {response.status_code}", 
                              response_data=response_data)
                return False
                
        except Exception as e:
            self.log_result("Progress Photos - POST", False, error=f"Exception: {str(e)}")
            return False
    
    def test_supplements_log_detailed(self):
        """Test supplements log with detailed error analysis"""
        print("🔍 Testing Supplements Log (POST /api/user/supplements/log)")
        
        try:
            # First create and assign a supplement
            admin_headers = {"Authorization": f"Bearer {self.admin_token}"}
            
            # Create supplement
            supplement_data = {
                "name": "Test Protein Powder",
                "description": "Whey protein for muscle building",
                "dosage": "30g",
                "timing": "Post workout"
            }
            
            create_response = self.session.post(f"{BASE_URL}/admin/supplements", json=supplement_data, headers=admin_headers)
            
            if create_response.status_code != 200:
                self.log_result("Supplements - Create", False, error=f"Failed to create supplement: {create_response.status_code}")
                return False
            
            supplement = create_response.json()
            supplement_id = supplement.get("id")
            
            # Assign supplement to user
            assignment_data = {
                "user_id": self.test_user_id,
                "supplement_id": supplement_id,
                "dosage": "30g",
                "timing": "After workout",
                "notes": "Test assignment"
            }
            
            assign_response = self.session.post(f"{BASE_URL}/admin/supplements/assign", json=assignment_data, headers=admin_headers)
            
            if assign_response.status_code != 200:
                self.log_result("Supplements - Assign", False, error=f"Failed to assign supplement: {assign_response.status_code}")
                return False
            
            # Now test user logging supplement
            user_headers = {"Authorization": f"Bearer {self.user_token}"}
            
            log_data = {
                "supplement_id": supplement_id,
                "taken": True
            }
            
            response = self.session.post(f"{BASE_URL}/user/supplements/log", json=log_data, headers=user_headers)
            
            print(f"Request URL: {BASE_URL}/user/supplements/log")
            print(f"Request Headers: {user_headers}")
            print(f"Request Data: {json.dumps(log_data, indent=2)}")
            print(f"Response Status: {response.status_code}")
            print(f"Response Headers: {dict(response.headers)}")
            
            try:
                response_data = response.json()
                print(f"Response Data: {json.dumps(response_data, indent=2)}")
            except:
                print(f"Response Text: {response.text}")
                response_data = {"raw_text": response.text}
            
            if response.status_code == 200:
                if "id" in response_data and "supplement_name" in response_data:
                    self.log_result("Supplements Log - POST", True, f"Supplement logged: {response_data['supplement_name']}")
                    return True
                else:
                    self.log_result("Supplements Log - POST", False, 
                                  error="Missing required fields in response", 
                                  response_data=response_data)
                    return False
            else:
                self.log_result("Supplements Log - POST", False, 
                              error=f"HTTP {response.status_code}", 
                              response_data=response_data)
                return False
                
        except Exception as e:
            self.log_result("Supplements Log - POST", False, error=f"Exception: {str(e)}")
            return False
    
    def test_diet_plan_update_detailed(self):
        """Test diet plan update with detailed error analysis"""
        print("🔍 Testing Diet Plan Update (PUT /api/admin/diet-plans/{id})")
        
        try:
            admin_headers = {"Authorization": f"Bearer {self.admin_token}"}
            
            # First create a diet plan
            plan_data = {
                "name": "Test Diet Plan",
                "description": "Test plan for weight loss",
                "meals": [
                    {
                        "meal_type": "breakfast",
                        "name": "Oats with fruits",
                        "recipe": "Mix oats with milk and fruits",
                        "calories": 300,
                        "protein_g": 15,
                        "carbs_g": 45,
                        "fat_g": 8
                    }
                ],
                "total_calories": 1800,
                "assigned_to": [self.test_user_id]
            }
            
            create_response = self.session.post(f"{BASE_URL}/admin/diet-plans", json=plan_data, headers=admin_headers)
            
            if create_response.status_code != 200:
                self.log_result("Diet Plan - Create", False, error=f"Failed to create diet plan: {create_response.status_code}")
                return False
            
            plan = create_response.json()
            plan_id = plan.get("id")
            
            # Now update the plan
            update_data = {
                "name": "Updated Test Diet Plan",
                "description": "Updated description for weight loss",
                "meals": [
                    {
                        "meal_type": "breakfast",
                        "name": "Updated Oats with fruits",
                        "recipe": "Updated recipe with more protein",
                        "calories": 350,
                        "protein_g": 20,
                        "carbs_g": 45,
                        "fat_g": 10
                    }
                ],
                "total_calories": 2000,
                "assigned_to": [self.test_user_id]
            }
            
            response = self.session.put(f"{BASE_URL}/admin/diet-plans/{plan_id}", json=update_data, headers=admin_headers)
            
            print(f"Request URL: {BASE_URL}/admin/diet-plans/{plan_id}")
            print(f"Request Headers: {admin_headers}")
            print(f"Request Data Keys: {list(update_data.keys())}")
            print(f"Response Status: {response.status_code}")
            print(f"Response Headers: {dict(response.headers)}")
            
            try:
                response_data = response.json()
                print(f"Response Data: {json.dumps(response_data, indent=2)}")
            except:
                print(f"Response Text: {response.text}")
                response_data = {"raw_text": response.text}
            
            if response.status_code == 200:
                if "id" in response_data and "name" in response_data:
                    self.log_result("Diet Plan Update - PUT", True, f"Plan updated: {response_data['name']}")
                    return True
                else:
                    self.log_result("Diet Plan Update - PUT", False, 
                                  error="Missing required fields in response", 
                                  response_data=response_data)
                    return False
            else:
                self.log_result("Diet Plan Update - PUT", False, 
                              error=f"HTTP {response.status_code}", 
                              response_data=response_data)
                return False
                
        except Exception as e:
            self.log_result("Diet Plan Update - PUT", False, error=f"Exception: {str(e)}")
            return False
    
    def test_session_booking_detailed(self):
        """Test session booking with detailed error analysis"""
        print("🔍 Testing Session Booking (POST /api/user/sessions)")
        
        try:
            user_headers = {"Authorization": f"Bearer {self.user_token}"}
            
            # Try booking a session for tomorrow with different time slots
            tomorrow = (datetime.now() + timedelta(days=1)).strftime("%Y-%m-%d")
            
            time_slots = ["09:00", "11:00", "14:00", "16:00", "18:00"]
            
            for time_slot in time_slots:
                booking_data = {
                    "date": tomorrow,
                    "time_slot": time_slot,
                    "notes": f"Test session booking at {time_slot}"
                }
                
                response = self.session.post(f"{BASE_URL}/user/sessions", json=booking_data, headers=user_headers)
                
                print(f"Request URL: {BASE_URL}/user/sessions")
                print(f"Request Headers: {user_headers}")
                print(f"Request Data: {json.dumps(booking_data, indent=2)}")
                print(f"Response Status: {response.status_code}")
                print(f"Response Headers: {dict(response.headers)}")
                
                try:
                    response_data = response.json()
                    print(f"Response Data: {json.dumps(response_data, indent=2)}")
                except:
                    print(f"Response Text: {response.text}")
                    response_data = {"raw_text": response.text}
                
                if response.status_code == 200:
                    if "id" in response_data and "date" in response_data:
                        self.log_result("Session Booking - POST", True, 
                                      f"Session booked for {response_data['date']} at {response_data['time_slot']}")
                        return True
                    else:
                        self.log_result("Session Booking - POST", False, 
                                      error="Missing required fields in response", 
                                      response_data=response_data)
                        return False
                elif response.status_code == 400 and "already booked" in response.text:
                    print(f"Time slot {time_slot} already booked, trying next...")
                    continue
                else:
                    self.log_result("Session Booking - POST", False, 
                                  error=f"HTTP {response.status_code}", 
                                  response_data=response_data)
                    return False
            
            # If all time slots failed
            self.log_result("Session Booking - POST", False, 
                          error="All time slots already booked or other error")
            return False
                
        except Exception as e:
            self.log_result("Session Booking - POST", False, error=f"Exception: {str(e)}")
            return False
    
    def run_focused_tests(self):
        """Run focused tests on previously failing endpoints"""
        print("🎯 Running Focused Backend API Tests")
        print("=" * 60)
        print(f"Base URL: {BASE_URL}")
        print(f"Focus: Previously failing endpoints from review request")
        print("=" * 60)
        print()
        
        if not self.setup_authentication():
            print("❌ Cannot proceed without authentication")
            return False
        
        print("\n🔍 DETAILED TESTING OF PREVIOUSLY FAILING ENDPOINTS")
        print("=" * 60)
        
        tests = [
            ("Step Tracking", self.test_step_tracking_detailed),
            ("Progress Photos", self.test_progress_photos_detailed),
            ("Supplements Log", self.test_supplements_log_detailed),
            ("Diet Plan Update", self.test_diet_plan_update_detailed),
            ("Session Booking", self.test_session_booking_detailed)
        ]
        
        passed = 0
        total = len(tests)
        
        for test_name, test_func in tests:
            print(f"\n{'='*20} {test_name} {'='*20}")
            if test_func():
                passed += 1
            print("-" * 60)
        
        # Summary
        print("\n" + "=" * 60)
        print("📊 FOCUSED TEST SUMMARY")
        print("=" * 60)
        print(f"Total Tests: {total}")
        print(f"Passed: {passed}")
        print(f"Failed: {total - passed}")
        print(f"Success Rate: {(passed/total)*100:.1f}%")
        print()
        
        # Detailed results
        for result in self.results:
            print(f"{result['status']}: {result['test']}")
            if result['details']:
                print(f"   {result['details']}")
            if result['error']:
                print(f"   Error: {result['error']}")
        
        return passed == total

if __name__ == "__main__":
    tester = FocusedTester()
    success = tester.run_focused_tests()
    
    if success:
        print("\n🎉 All focused tests passed! Previously failing endpoints are now working.")
    else:
        print("\n⚠️  Some endpoints still have issues. Check the detailed logs above.")