#!/usr/bin/env python3
"""
Tritri Integration Tests
Tests the complete user flows using HTTP requests and browser simulation
"""

import requests
import time
import json
import sys

# Configuration
BASE_URL = "http://localhost:3002"
API_BASE = "http://localhost:8000"

class TritriIntegrationTest:
    def __init__(self):
        self.session = requests.Session()

    def test_health_check(self):
        """Test if both frontend and backend are running"""
        try:
            # Test backend
            response = requests.get(f"{API_BASE}/")
            assert response.status_code == 200
            print("✅ Backend is healthy")

            # Test frontend
            response = requests.get(BASE_URL)
            assert response.status_code == 200
            assert "Tritri" in response.text
            print("✅ Frontend is healthy")
            return True
        except Exception as e:
            print(f"❌ Health check failed: {e}")
            return False

    def test_trip_creation_api(self):
        """Test trip creation via API"""
        trip_data = {
            "name": "Integration Test Trip",
            "creator_name": "Test User",
            "currency_code": "USD"
        }

        response = requests.post(f"{API_BASE}/api/trips/", json=trip_data)
        assert response.status_code == 200

        trip = response.json()
        assert trip["name"] == "Integration Test Trip"
        assert "share_code" in trip
        assert len(trip["share_code"]) == 6

        print(f"✅ Created trip '{trip['name']}' with code {trip['share_code']}")
        return trip

    def test_trip_joining_api(self, share_code):
        """Test trip joining via API"""
        response = requests.get(f"{API_BASE}/api/trips/share/{share_code}")
        assert response.status_code == 200

        trip_data = response.json()
        assert "participants" in trip_data
        assert len(trip_data["participants"]) >= 1  # At least creator

        print(f"✅ Found trip with {len(trip_data['participants'])} participants")
        return trip_data

    def test_participant_addition_api(self, trip_id):
        """Test adding participant via API"""
        participant_data = {"name": "Additional Participant"}
        response = requests.post(
            f"{API_BASE}/api/participants/{trip_id}/participants",
            json=participant_data
        )
        assert response.status_code == 200

        participant = response.json()
        assert participant["name"] == "Additional Participant"
        print(f"✅ Added participant '{participant['name']}'")
        return participant

    def test_user_identification_api(self, trip_id, participant_id):
        """Test user identification via API"""
        device_id = f"test_device_{int(time.time())}"
        response = requests.post(
            f"{API_BASE}/api/auth/identify",
            params={
                "trip_id": trip_id,
                "participant_id": participant_id,
                "device_id": device_id
            }
        )
        assert response.status_code == 200

        result = response.json()
        assert "message" in result
        print(f"✅ User identified: {result.get('participant_name', 'Unknown')}")
        return result

    def test_frontend_accessibility(self):
        """Test frontend accessibility via HTTP requests"""
        try:
            # Test main page
            response = requests.get(BASE_URL)
            assert response.status_code == 200
            assert "Tritri" in response.text
            assert "Split expenses fairly" in response.text

            # Test join page
            response = requests.get(f"{BASE_URL}/join")
            assert response.status_code == 200
            assert "Join Trip" in response.text

            # Test dashboard page (should redirect to home if no trips)
            response = requests.get(f"{BASE_URL}/dashboard")
            # Dashboard should work (might redirect if no trips)
            assert response.status_code in [200, 302]

            print("✅ Frontend pages accessible")
            return True

        except Exception as e:
            print(f"❌ Frontend accessibility test failed: {e}")
            return False

    def test_multi_trip_flow(self):
        """Test complete multi-trip user flow"""
        print("\n🔄 Testing Multi-Trip Flow...")

        # Create first trip
        trip1 = self.test_trip_creation_api()

        # Create second trip
        trip2_data = {
            "name": "Second Integration Trip",
            "creator_name": "Multi Trip User",
            "currency_code": "EUR"
        }
        response = requests.post(f"{API_BASE}/api/trips/", json=trip2_data)
        trip2 = response.json()

        # Add participant to first trip
        participant = self.test_participant_addition_api(trip1["id"])

        # Test identification with both trips
        trip1_response = requests.get(f"{API_BASE}/api/trips/{trip1['id']}")
        trip1_data = trip1_response.json()

        # Find the participant we added
        target_participant = None
        for p in trip1_data["participants"]:
            if p["name"] == "Additional Participant":
                target_participant = p
                break

        if target_participant:
            self.test_user_identification_api(trip1["id"], target_participant["id"])

        print(f"✅ Multi-trip flow successful - User has access to both trips")
        return [trip1, trip2]

    def run_all_tests(self):
        """Run all integration tests"""
        print("🚀 Starting Tritri Integration Tests")
        print("=" * 50)

        tests_passed = 0
        total_tests = 0

        # Health check
        total_tests += 1
        if self.test_health_check():
            tests_passed += 1

        # API tests
        total_tests += 1
        trip = self.test_trip_creation_api()
        tests_passed += 1

        total_tests += 1
        self.test_trip_joining_api(trip["share_code"])
        tests_passed += 1

        total_tests += 1
        participant = self.test_participant_addition_api(trip["id"])
        tests_passed += 1

        total_tests += 1
        self.test_user_identification_api(trip["id"], participant["id"])
        tests_passed += 1

        # Multi-trip flow
        total_tests += 1
        self.test_multi_trip_flow()
        tests_passed += 1

        # Frontend accessibility tests
        total_tests += 1
        if self.test_frontend_accessibility():
            tests_passed += 1

        # Results
        print("\n" + "=" * 50)
        print(f"📊 Test Results: {tests_passed}/{total_tests} tests passed")

        if tests_passed == total_tests:
            print("🎉 All integration tests passed!")
            print("\n✅ Verified Functionality:")
            print("  • API endpoints working correctly")
            print("  • Trip creation and management")
            print("  • User identification and device linking")
            print("  • Multi-trip support")
            print("  • Participant management")
            return True
        else:
            print("❌ Some tests failed!")
            return False

def main():
    """Main test runner"""
    tester = TritriIntegrationTest()

    try:
        success = tester.run_all_tests()
        return 0 if success else 1
    except Exception as e:
        print(f"❌ Test suite failed with error: {e}")
        return 1

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