"""Tests for multiple question solutions in the same file."""

import pytest


def test_multi_question_submission_q1_only(api_client, valid_token):
    """Test submitting a file with multiple solutions, using function_name to select Q1."""
    code = '''def helper_function(arr, val):
    """Shared helper used by multiple solutions."""
    try:
        return arr.index(val)
    except ValueError:
        return -1

def solution_q1(nums, target):
    """Solution for Two Sum (Q1)."""
    seen = {}
    for i, num in enumerate(nums):
        complement = target - num
        if complement in seen:
            return [seen[complement], i]
        seen[num] = i
    return []

def solution_q2(nums, target):
    """Solution for some other question (Q2)."""
    # This function exists but should not be tested
    return [99, 99]

def another_helper():
    """Another helper function."""
    return 42
'''
    
    # Submit with function_name='solution_q1'
    response = api_client['submit'](
        code=code,
        function_name='solution_q1',
        token=valid_token
    )
    
    assert response.status_code == 200
    data = response.json()
    
    # Should test solution_q1 and pass all tests
    assert data['success'] is True
    assert data['passed'] == 7
    assert data['total'] == 7


def test_multi_question_uses_correct_function(api_client, valid_token):
    """Test that the correct function is tested based on function_name parameter."""
    code = '''def correct_solution(nums, target):
    """Correct solution for Two Sum."""
    seen = {}
    for i, num in enumerate(nums):
        complement = target - num
        if complement in seen:
            return [seen[complement], i]
        seen[num] = i
    return []

def wrong_solution(nums, target):
    """Wrong solution."""
    return [99, 99]
'''
    
    # Test with correct function
    response = api_client['submit'](
        code=code,
        function_name='correct_solution',
        token=valid_token
    )
    
    assert response.status_code == 200
    data = response.json()
    assert data['success'] is True
    
    # Test with wrong function
    response = api_client['submit'](
        code=code,
        function_name='wrong_solution',
        token=valid_token
    )
    
    assert response.status_code == 200
    data = response.json()
    assert data['success'] is False


def test_multi_question_with_shared_imports(api_client, valid_token):
    """Test that multiple solutions can share imports."""
    code = '''from typing import List, Dict

def solution_q1(nums: List[int], target: int) -> List[int]:
    """Solution for Two Sum with type hints."""
    seen: Dict[int, int] = {}
    for i, num in enumerate(nums):
        complement = target - num
        if complement in seen:
            return [seen[complement], i]
        seen[num] = i
    return []

def solution_q2(nums: List[int]) -> int:
    """Some other solution with type hints."""
    return len(nums)
'''
    
    response = api_client['submit'](
        code=code,
        function_name='solution_q1',
        token=valid_token
    )
    
    assert response.status_code == 200
    data = response.json()
    
    assert data['success'] is True


def test_helper_functions_available_to_solution(api_client, valid_token):
    """Test that helper functions are available and work correctly in submitted code."""
    code = '''def find_complement(seen_dict, target, current):
    """Helper to find complement."""
    complement = target - current
    if complement in seen_dict:
        return seen_dict[complement]
    return None

def two_sum(nums, target):
    """Solution using helper."""
    seen = {}
    for i, num in enumerate(nums):
        comp_idx = find_complement(seen, target, num)
        if comp_idx is not None:
            return [comp_idx, i]
        seen[num] = i
    return []
'''
    
    response = api_client['submit'](
        code=code,
        function_name='two_sum',
        token=valid_token
    )
    
    assert response.status_code == 200
    data = response.json()
    
    # Should work correctly with helper
    assert data['success'] is True
    assert data['passed'] == 7


def test_class_based_solution(api_client, valid_token):
    """Test that class-based solutions work (if someone wants to use OOP)."""
    code = '''class Solution:
    def find_two_sum(self, nums, target):
        """Instance method solution."""
        seen = {}
        for i, num in enumerate(nums):
            complement = target - num
            if complement in seen:
                return [seen[complement], i]
            seen[num] = i
        return []

def two_sum(nums, target):
    """Wrapper function that uses the class."""
    solver = Solution()
    return solver.find_two_sum(nums, target)
'''
    
    response = api_client['submit'](
        code=code,
        function_name='two_sum',
        token=valid_token
    )
    
    assert response.status_code == 200
    data = response.json()
    
    assert data['success'] is True


def test_nested_functions(api_client, valid_token):
    """Test that solutions with nested functions work correctly."""
    code = '''def two_sum(nums, target):
    """Solution with nested helper."""
    def check_pair(i, j):
        return nums[i] + nums[j] == target
    
    seen = {}
    for i, num in enumerate(nums):
        complement = target - num
        if complement in seen:
            j = seen[complement]
            if check_pair(j, i):
                return [j, i]
        seen[num] = i
    return []
'''
    
    response = api_client['submit'](
        code=code,
        function_name='two_sum',
        token=valid_token
    )
    
    assert response.status_code == 200
    data = response.json()
    
    assert data['success'] is True
