"""
Test client for interacting with the local Tong Nian challenge server.
"""

import requests
import io
import zipfile
from pathlib import Path


def test_health():
    """Check if server is running."""
    try:
        response = requests.get("http://localhost:5001/health")
        print(f"Health check: {response.json()}")
        return True
    except Exception as e:
        print(f"Error connecting to server: {e}")
        return False


def test_pow():
    """Get proof-of-work challenge (should be disabled in local mode)."""
    try:
        response = requests.get("http://localhost:5001/pow")
        data = response.json()
        print(f"Proof-of-work: {data}")
        return data
    except Exception as e:
        print(f"Error getting PoW: {e}")
        return None


def create_dummy_submission():
    """
    Create a dummy submission ZIP for testing.
    This will fail verification since it doesn't satisfy the paradox requirement,
    but it lets us test the endpoint.
    """
    refs_dir = Path("src/data/refs")
    
    zip_buffer = io.BytesIO()
    with zipfile.ZipFile(zip_buffer, 'w') as zf:
        for i in range(10):
            ref_path = refs_dir / f"ref_{i:02d}.png"
            if ref_path.exists():
                with open(ref_path, 'rb') as f:
                    data = f.read()
                # Create both img1 and img2 as copies of the reference
                # (this will pass MD5 check but fail classification check)
                zf.writestr(f"pair_{i:02d}_img1.png", data)
                zf.writestr(f"pair_{i:02d}_img2.png", data)
    
    return zip_buffer.getvalue()


def submit_test():
    """Submit a test ZIP file."""
    print("\nCreating test submission...")
    zip_data = create_dummy_submission()
    
    print(f"ZIP size: {len(zip_data)} bytes")
    print("Submitting to server...")
    
    try:
        response = requests.post(
            "http://localhost:5001/submit",
            files={"file": ("submission.zip", zip_data, "application/zip")}
        )
        
        result = response.json()
        print(f"\nResponse: {result}")
        
        if result.get("success"):
            print(f"\n🎉 SUCCESS! Flag: {result.get('flag')}")
        else:
            print("\n❌ Submission failed verification")
            print("This is expected - we need to solve the paradox!")
            
        return result
        
    except Exception as e:
        print(f"Error submitting: {e}")
        return None


def main():
    print("="*80)
    print("TONG NIAN CHALLENGE - LOCAL TEST CLIENT")
    print("="*80)
    
    print("\n1. Testing health endpoint...")
    if not test_health():
        print("\n❌ Server not running!")
        print("Start with: docker run -d -p 5001:5000 --name tong-nian-app -e POW_DIFFICULTY=0 tong-nian-adversarial")
        return
    
    print("\n2. Testing proof-of-work endpoint...")
    test_pow()
    
    print("\n3. Testing submission endpoint...")
    submit_test()
    
    print("\n" + "="*80)
    print("NEXT STEPS")
    print("="*80)
    print("""
To actually solve the challenge, you need to create a ZIP file where:
- Each pair has img1 and img2 with IDENTICAL MD5 hashes
- But img1 and img2 classify as DIFFERENT digits
- This requires advanced techniques like:
  * MD5 collision attacks (chosen-prefix collisions)
  * PNG format manipulation
  * Or discovering a bug in the verification logic

Good luck solving this extremely challenging puzzle! 🔐🤖
    """)


if __name__ == "__main__":
    main()
