#!/usr/bin/env python3
"""
Debug Bug Report Feature - Live Flask App Test
Tests the bug report functionality within the Flask app context.
"""
import os
from dotenv import load_dotenv
# Load environment variables like Flask does
basedir = os.path.abspath(os.path.dirname(__file__))
load_dotenv(os.path.join(basedir, '.env'))
def test_env_variables():
    """Test if environment variables are loaded correctly"""
    print("🔍 Testing Environment Variable Loading...")
    webhook_url = os.environ.get('SLACK_WEBHOOK_URL')
    print(f"SLACK_WEBHOOK_URL found: {bool(webhook_url)}")
    if webhook_url:
        print(f"Webhook URL: {webhook_url[:50]}...")
        # Test if it looks valid
        if webhook_url.startswith('https://hooks.slack.com/'):
            print("✅ Webhook URL format looks correct")
            return True
        else:
            print("❌ Webhook URL format may be incorrect")
            return False
    else:
        print("❌ SLACK_WEBHOOK_URL not found")
        return False
def test_slack_webhook_directly():
    """Test the Slack webhook directly"""
    print("\n📡 Testing Slack Webhook Directly...")
    import requests
    import json
    from datetime import datetime
    webhook_url = os.environ.get('SLACK_WEBHOOK_URL')
    if not webhook_url:
        print("❌ No webhook URL to test")
        return False
    # Test message
    test_message = {
        "text": "🧪 Bug Report Test from RateRight",
        "blocks": [
            {
                "type": "section",
                "text": {
                    "type": "mrkdwn",
                    "text": "*Test Bug Report*\nThis is a test to verify the bug report system is working correctly."
                }
            },
            {
                "type": "context",
                "elements": [
                    {
                        "type": "mrkdwn",
                        "text": f"Test Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
                    }
                ]
            }
        ]
    }
    try:
        response = requests.post(webhook_url, json=test_message, timeout=10)
        print(f"Response status: {response.status_code}")
        if response.status_code == 200:
            print("✅ Slack webhook test successful!")
            print("✅ Check your Slack channel for the test message")
            return True
        else:
            print(f"❌ Slack webhook failed: {response.status_code}")
            print(f"Response: {response.text}")
            return False
    except requests.exceptions.Timeout:
        print("❌ Slack webhook timeout - check your internet connection")
        return False
    except Exception as e:
        print(f"❌ Slack webhook error: {e}")
        return False
def test_flask_app_context():
    """Test bug report functionality in Flask app context"""
    print("\n🧪 Testing Bug Report in Flask Context...")
    try:
        from app import create_app
        from app.utils.slack import send_bug_report_to_slack
        app = create_app()
        with app.app_context():
            # Test bug report data
            bug_data = {
                'description': 'Test bug report - form submission testing',
                'page_url': 'http://localhost:5000/dashboard',
                'email': 'test@rateright.com.au'
            }
            request_info = {
                'ip': '127.0.0.1',
                'referrer': 'Direct',
                'user_agent': 'Mozilla/5.0 (Test Browser)'
            }
            print("🐛 Sending test bug report...")
            success = send_bug_report_to_slack(bug_data, request_info)
            if success:
                print("✅ Bug report sent successfully via Flask app!")
                print("✅ Check your Slack channel for the bug report")
                return True
            else:
                print("❌ Bug report failed to send")
                return False
    except Exception as e:
        print(f"❌ Flask app test error: {e}")
        import traceback
        print(f"Full error: {traceback.format_exc()}")
        return False
def main():
    """Run comprehensive bug report testing"""
    print("🚀 Bug Report Debug - Live Flask App Test")
    print("=" * 50)
    # Test 1: Environment variables
    env_success = test_env_variables()
    # Test 2: Direct webhook test
    webhook_success = test_slack_webhook_directly()
    # Test 3: Flask app context test
    flask_success = test_flask_app_context()
    print("\n" + "=" * 50)
    print("📋 Bug Report Debug Summary:")
    print("=" * 50)
    print(f"Environment Variables: {'✅' if env_success else '❌'}")
    print(f"Direct Slack Webhook: {'✅' if webhook_success else '❌'}")
    print(f"Flask App Integration: {'✅' if flask_success else '❌'}")
    if all([env_success, webhook_success, flask_success]):
        print("\n🎉 Bug Report System is Working!")
        print("🔧 Users should be able to report bugs successfully")
        print("📧 Bug reports will appear in your Slack channel")
    else:
        print("\n⚠️  Issues found - check the logs above")
        if not env_success:
            print("   → Environment variables not loading properly")
        if not webhook_success:
            print("   → Slack webhook not responding")
        if not flask_success:
            print("   → Flask integration has issues")
    print(f"\n🔧 To test the UI: Start Flask server with 'python run.py'")
    print(f"   Then visit any page and click the bug report button")
if __name__ == '__main__':
    main()
