#!/usr/bin/env python3
"""
Test script to verify the improved port detection patterns in taskapp.py
"""

import re
import os

def test_port_detection_patterns():
    """Test various port detection patterns against sample app.py content"""
    
    # Sample app.py content patterns that should be detected
    test_cases = [
        # Case 1: Simple PORT constant
        ("PORT = 8080", 8080, "PORT constant"),
        
        # Case 2: Lowercase port variable
        ("port = 8001", 8001, "lowercase port variable"),
        
        # Case 3: Server address tuple
        ("server_address = ('0.0.0.0', 8002)", 8002, "server_address tuple"),
        
        # Case 4: HTTPServer with tuple
        ("httpd = HTTPServer(('', 8003), MyHandler)", 8003, "HTTPServer tuple"),
        
        # Case 5: TCPServer pattern
        ("with socketserver.TCPServer(('', 8004), Handler) as httpd:", 8004, "TCPServer pattern"),
        
        # Case 6: Flask-style app.run
        ("app.run(host='0.0.0.0', port=8005)", 8005, "Flask app.run"),
        
        # Case 7: Complex HTTPServer pattern
        ('server = http.server.HTTPServer(("localhost", 8006), RequestHandler)', 8006, "Complex HTTPServer"),
        
        # Case 8: Indented PORT definition
        ("    PORT = 8007  # Server port", 8007, "Indented PORT with comment"),
        
        # Case 9: Mixed case
        ("Port = 8008", 8008, "Mixed case Port"),
        
        # Case 10: String quotes in server address
        ('server_address = ("127.0.0.1", 8009)', 8009, "server_address with quotes"),
    ]
    
    print("Testing Port Detection Patterns")
    print("=" * 50)
    
    passed = 0
    failed = 0
    
    for i, (content, expected_port, description) in enumerate(test_cases, 1):
        print(f"\nTest {i}: {description}")
        print(f"Content: {content}")
        print(f"Expected: {expected_port}")
        
        detected_port = detect_port_from_content(content)
        
        if detected_port == expected_port:
            print(f"✅ PASSED: Detected port {detected_port}")
            passed += 1
        else:
            print(f"❌ FAILED: Detected port {detected_port}, expected {expected_port}")
            failed += 1
    
    print(f"\n" + "=" * 50)
    print(f"Results: {passed} passed, {failed} failed")
    
    if failed == 0:
        print("🎉 All tests passed! Port detection should work correctly.")
    else:
        print("⚠️  Some tests failed. Port detection may need improvement.")

def detect_port_from_content(content):
    """
    Simulate the port detection logic from taskapp.py
    """
    import re
    
    # Pattern 1: PORT = 8080 (case insensitive)
    port_match = re.search(r'^\s*PORT\s*=\s*(\d+)', content, re.MULTILINE | re.IGNORECASE)
    if port_match:
        return int(port_match.group(1))
    
    # Pattern 2: port = 8080 (case insensitive)
    port_match = re.search(r'^\s*port\s*=\s*(\d+)', content, re.MULTILINE | re.IGNORECASE)
    if port_match:
        return int(port_match.group(1))
    
    # Pattern 3: server_address = ('0.0.0.0', 8004) or server_address = ("", 8004)
    port_match = re.search(r'server_address\s*=\s*\([^,]+,\s*(\d+)\)', content)
    if port_match:
        return int(port_match.group(1))
    
    # Pattern 4: HTTPServer(('0.0.0.0', 8004), Handler) or HTTPServer(("", 8004), Handler)
    port_match = re.search(r'HTTPServer\(\s*\(["\']?[^"\']*["\']?,\s*(\d+)\)', content)
    if port_match:
        return int(port_match.group(1))
    
    # Pattern 5: TCPServer(("", 8080), Handler) or TCPServer(('', 8080), Handler)
    port_match = re.search(r'TCPServer\(\s*\(["\']?[^"\']*["\']?,\s*(\d+)\)', content)
    if port_match:
        return int(port_match.group(1))
    
    # Pattern 6: app.run(port=8080) or app.run(host='0.0.0.0', port=8080)
    port_match = re.search(r'\.run\([^)]*port\s*=\s*(\d+)', content)
    if port_match:
        return int(port_match.group(1))
    
    # Pattern 7: Any 4-digit number in the 8000-9000 range (last resort)
    all_numbers = re.findall(r'\b(8\d{3})\b', content)
    for num_str in all_numbers:
        port = int(num_str)
        if 8000 <= port <= 9000:
            return port
    
    return None

if __name__ == "__main__":
    test_port_detection_patterns() 