#!/usr/bin/env python3
"""
KMC Performance Monitoring System - Backend API Test Suite
Tests all API endpoints and functionality systematically
"""
import requests
import sys
import json
from datetime import datetime, timedelta
import uuid

# Get the backend URL from frontend env
BASE_URL = "http://localhost:8001"  # Default
try:
    with open('/app/frontend/.env', 'r') as f:
        for line in f:
            if line.startswith('REACT_APP_BACKEND_URL='):
                BASE_URL = line.split('=')[1].strip()
                break
except FileNotFoundError:
    pass

API_BASE = f"{BASE_URL}/api"

class KMCAPITester:
    def __init__(self):
        self.session = requests.Session()
        self.token = None
        self.admin_user = None
        self.shops = []
        self.test_results = {
            "total_tests": 0,
            "passed": 0,
            "failed": 0,
            "errors": []
        }
        
    def log_result(self, test_name, success, details=""):
        """Log test result"""
        self.test_results["total_tests"] += 1
        if success:
            self.test_results["passed"] += 1
            print(f"✅ {test_name}")
        else:
            self.test_results["failed"] += 1 
            self.test_results["errors"].append(f"{test_name}: {details}")
            print(f"❌ {test_name} - {details}")
    
    def test_health_check(self):
        """Test basic health endpoint"""
        try:
            response = self.session.get(f"{API_BASE}/health")
            success = response.status_code == 200
            details = f"Status: {response.status_code}"
            if success:
                details += f", Response: {response.json()}"
            self.log_result("Health Check", success, details)
            return success
        except Exception as e:
            self.log_result("Health Check", False, str(e))
            return False
    
    def test_seed_data(self):
        """Seed initial data"""
        try:
            response = self.session.post(f"{API_BASE}/seed-data")
            # Should return success even if data already exists
            success = response.status_code in [200, 400]  # 400 if already seeded
            data = response.json()
            details = f"Status: {response.status_code}, Message: {data.get('message', 'No message')}"
            self.log_result("Seed Data", success, details)
            return success
        except Exception as e:
            self.log_result("Seed Data", False, str(e))
            return False
    
    def test_login(self):
        """Test admin login"""
        try:
            login_data = {
                "email": "admin@kmc.go.ke", 
                "password": "admin123"
            }
            response = self.session.post(f"{API_BASE}/auth/login", json=login_data)
            success = response.status_code == 200
            
            if success:
                data = response.json()
                self.token = data.get("access_token")
                self.admin_user = data.get("user")
                self.session.headers.update({"Authorization": f"Bearer {self.token}"})
                details = f"Logged in as {self.admin_user.get('email')} ({self.admin_user.get('role')})"
            else:
                details = f"Status: {response.status_code}, Response: {response.text}"
                
            self.log_result("Admin Login", success, details)
            return success
        except Exception as e:
            self.log_result("Admin Login", False, str(e))
            return False
    
    def test_me_endpoint(self):
        """Test /auth/me endpoint"""
        try:
            response = self.session.get(f"{API_BASE}/auth/me")
            success = response.status_code == 200
            if success:
                user_data = response.json()
                details = f"User: {user_data.get('email')}, Role: {user_data.get('role')}"
            else:
                details = f"Status: {response.status_code}"
            self.log_result("Get Current User", success, details)
            return success
        except Exception as e:
            self.log_result("Get Current User", False, str(e))
            return False
    
    def test_get_shops(self):
        """Test fetching shops"""
        try:
            response = self.session.get(f"{API_BASE}/shops")
            success = response.status_code == 200
            if success:
                self.shops = response.json()
                details = f"Found {len(self.shops)} shops"
            else:
                details = f"Status: {response.status_code}"
            self.log_result("Get Shops", success, details)
            return success
        except Exception as e:
            self.log_result("Get Shops", False, str(e))
            return False
    
    def test_get_users(self):
        """Test fetching users (admin only)"""
        try:
            response = self.session.get(f"{API_BASE}/users")
            success = response.status_code == 200
            if success:
                users = response.json()
                details = f"Found {len(users)} users"
            else:
                details = f"Status: {response.status_code}"
            self.log_result("Get Users", success, details)
            return success
        except Exception as e:
            self.log_result("Get Users", False, str(e))
            return False
    
    def test_dashboard_stats(self):
        """Test dashboard stats endpoint"""
        try:
            response = self.session.get(f"{API_BASE}/dashboard/stats")
            success = response.status_code == 200
            if success:
                stats = response.json()
                details = f"Sales today: {stats.get('total_sales_today', 0)}, Pending: {stats.get('pending_submissions', 0)}"
            else:
                details = f"Status: {response.status_code}"
            self.log_result("Dashboard Stats", success, details)
            return success
        except Exception as e:
            self.log_result("Dashboard Stats", False, str(e))
            return False
    
    def test_dashboard_charts(self):
        """Test dashboard chart endpoints"""
        endpoints = [
            "sales-by-shop",
            "payment-breakdown", 
            "stock-position",
            "sales-trend",
            "out-of-stock"
        ]
        
        all_success = True
        for endpoint in endpoints:
            try:
                response = self.session.get(f"{API_BASE}/dashboard/{endpoint}")
                success = response.status_code == 200
                if success:
                    data = response.json()
                    details = f"Returned {len(data) if isinstance(data, list) else 'data'}"
                else:
                    details = f"Status: {response.status_code}"
                self.log_result(f"Chart Data: {endpoint}", success, details)
                if not success:
                    all_success = False
            except Exception as e:
                self.log_result(f"Chart Data: {endpoint}", False, str(e))
                all_success = False
        
        return all_success
    
    def test_sales_crud(self):
        """Test sales CRUD operations"""
        if not self.shops:
            self.log_result("Sales CRUD", False, "No shops available")
            return False
            
        # Test GET sales
        try:
            response = self.session.get(f"{API_BASE}/sales")
            get_success = response.status_code == 200
            if get_success:
                existing_sales = response.json()
                details = f"Found {len(existing_sales)} existing sales"
            else:
                details = f"GET Status: {response.status_code}"
            self.log_result("Get Sales", get_success, details)
        except Exception as e:
            self.log_result("Get Sales", False, str(e))
            return False
        
        # Test POST new sale
        try:
            shop_id = self.shops[0]["id"]
            today = datetime.now().strftime("%Y-%m-%d")
            
            sale_data = {
                "shop_id": shop_id,
                "date": today,
                "kmc_products_total": 250000.00,
                "kenchic_total": 15000.00,
                "payment_breakdown": {
                    "coop": 150000.00,
                    "kcb": 50000.00,
                    "ecitizen": 35000.00,
                    "swipe": 30000.00
                },
                "line_items": [],
                "notes": "Test sales entry"
            }
            
            response = self.session.post(f"{API_BASE}/sales", json=sale_data)
            post_success = response.status_code == 200
            
            if post_success:
                sale = response.json()
                sale_id = sale["id"]
                details = f"Created sale {sale_id}, Total: {sale['total_sales']}"
                
                # Test submission
                response = self.session.post(f"{API_BASE}/sales/{sale_id}/submit")
                submit_success = response.status_code == 200
                self.log_result("Submit Sales", submit_success, f"Status: {response.status_code}")
                
                # Test posting (admin only)
                response = self.session.post(f"{API_BASE}/sales/{sale_id}/post")
                post_admin_success = response.status_code == 200
                self.log_result("Post Sales", post_admin_success, f"Status: {response.status_code}")
                
            else:
                details = f"POST Status: {response.status_code}, Response: {response.text}"
            
            self.log_result("Create Sales", post_success, details)
            return post_success
            
        except Exception as e:
            self.log_result("Create Sales", False, str(e))
            return False
    
    def test_stock_operations(self):
        """Test stock operations"""
        # Test GET latest stock
        try:
            response = self.session.get(f"{API_BASE}/stock/latest")
            success = response.status_code == 200
            if success:
                stock_data = response.json()
                details = f"HQ Stock: {'✓' if stock_data.get('hq') else '✗'}, Kibarani: {'✓' if stock_data.get('kibarani') else '✗'}"
            else:
                details = f"Status: {response.status_code}"
            self.log_result("Get Latest Stock", success, details)
        except Exception as e:
            self.log_result("Get Latest Stock", False, str(e))
            return False
        
        # Test POST stock entry
        try:
            today = datetime.now().strftime("%Y-%m-%d")
            stock_data = {
                "location": "hq",
                "date": today,
                "stock_items": [
                    {
                        "category": "MOB Beef",
                        "product_name": "MOB Beef", 
                        "quantity_kg": 5000.0,
                        "unit": "kg",
                        "status": "available"
                    },
                    {
                        "category": "KMC Products",
                        "subcategory": "VAP",
                        "product_name": "Sausages",
                        "quantity_kg": 200.0, 
                        "unit": "kg",
                        "status": "available"
                    }
                ],
                "notes": "Test stock entry"
            }
            
            response = self.session.post(f"{API_BASE}/stock", json=stock_data)
            success = response.status_code == 200
            if success:
                stock = response.json()
                details = f"Created stock entry for {stock['location']}, Items: {len(stock['stock_items'])}"
            else:
                details = f"Status: {response.status_code}, Response: {response.text}"
            self.log_result("Create Stock Entry", success, details)
            return success
            
        except Exception as e:
            self.log_result("Create Stock Entry", False, str(e))
            return False
    
    def test_livestock_operations(self):
        """Test livestock operations"""
        # Test GET livestock
        try:
            response = self.session.get(f"{API_BASE}/livestock")
            get_success = response.status_code == 200
            if get_success:
                livestock_data = response.json()
                details = f"Found {len(livestock_data)} livestock entries"
            else:
                details = f"GET Status: {response.status_code}"
            self.log_result("Get Livestock", get_success, details)
        except Exception as e:
            self.log_result("Get Livestock", False, str(e))
            return False
            
        # Test POST livestock
        try:
            today = datetime.now().strftime("%Y-%m-%d")
            livestock_data = {
                "date": today,
                "cattle_received": 85,
                "shoats_received": 150,
                "cattle_slaughtered": 70,
                "shoats_slaughtered": 120,
                "notes": "Test livestock entry"
            }
            
            response = self.session.post(f"{API_BASE}/livestock", json=livestock_data)
            success = response.status_code == 200
            if success:
                livestock = response.json()
                details = f"Cattle: {livestock['cattle_received']}, Shoats: {livestock['shoats_received']}"
            else:
                details = f"Status: {response.status_code}, Response: {response.text}"
            self.log_result("Create Livestock Entry", success, details)
            return success
            
        except Exception as e:
            self.log_result("Create Livestock Entry", False, str(e))
            return False
    
    def test_audit_logs(self):
        """Test audit logs"""
        try:
            response = self.session.get(f"{API_BASE}/audit-logs")
            success = response.status_code == 200
            if success:
                logs = response.json()
                details = f"Found {len(logs)} audit log entries"
            else:
                details = f"Status: {response.status_code}"
            self.log_result("Get Audit Logs", success, details)
            return success
        except Exception as e:
            self.log_result("Get Audit Logs", False, str(e))
            return False

    def run_all_tests(self):
        """Run all API tests"""
        print("🔍 Starting KMC Backend API Tests...\n")
        
        # Basic connectivity and setup
        if not self.test_health_check():
            print("❌ Health check failed - cannot continue")
            return False
            
        if not self.test_seed_data():
            print("❌ Seed data failed")
            return False
            
        if not self.test_login():
            print("❌ Login failed - cannot test authenticated endpoints")
            return False
        
        # Authenticated tests
        self.test_me_endpoint()
        self.test_get_shops()
        self.test_get_users()
        
        # Dashboard tests
        self.test_dashboard_stats()
        self.test_dashboard_charts()
        
        # Business logic tests  
        self.test_sales_crud()
        self.test_stock_operations()
        self.test_livestock_operations()
        self.test_audit_logs()
        
        # Print summary
        print(f"\n📊 Test Results Summary:")
        print(f"Total Tests: {self.test_results['total_tests']}")
        print(f"Passed: {self.test_results['passed']}")
        print(f"Failed: {self.test_results['failed']}")
        print(f"Success Rate: {(self.test_results['passed']/self.test_results['total_tests']*100):.1f}%")
        
        if self.test_results['errors']:
            print(f"\n❌ Failed Tests:")
            for error in self.test_results['errors']:
                print(f"  - {error}")
        
        return self.test_results['failed'] == 0


def main():
    """Main test runner"""
    print("🚀 KMC Performance Monitoring System - Backend API Test Suite")
    print(f"🔗 Testing API at: {API_BASE}\n")
    
    tester = KMCAPITester()
    success = tester.run_all_tests()
    
    if success:
        print("\n✅ All backend tests passed!")
        return 0
    else:
        print(f"\n❌ {tester.test_results['failed']} test(s) failed")
        return 1

if __name__ == "__main__":
    sys.exit(main())