#!/bin/bash

# This script initializes the bugfix_repo with branches and a merge conflict scenario
# Run this script to set up the git exercise

REPO_DIR="$(dirname "$0")/bugfix_repo"

# Clean up if exists
rm -rf "$REPO_DIR"
mkdir -p "$REPO_DIR"
cd "$REPO_DIR"

# Initialize repo
git init -b main
git config user.email "interviewer@company.com"
git config user.name "Interview Setup"

# Create initial files
cat > user_validator.py << 'EOF'
"""
User validation module for the application.
"""

import re


def validate_email(email):
    """Validate email format."""
    if not email:
        return False
    pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
    return bool(re.match(pattern, email))


def validate_username(username):
    """Validate username format."""
    if not username:
        return False
    if len(username) < 3:
        return False
    if len(username) > 20:
        return False
    return username.isalnum()


def validate_password(password):
    """Validate password strength."""
    if not password:
        return False
    if len(password) < 8:
        return False
    return True


def validate_user(user_data):
    """Validate complete user data."""
    errors = []
    
    if not validate_email(user_data.get('email', '')):
        errors.append('Invalid email format')
    
    if not validate_username(user_data.get('username', '')):
        errors.append('Invalid username')
    
    if not validate_password(user_data.get('password', '')):
        errors.append('Password too weak')
    
    return len(errors) == 0, errors
EOF

cat > README.md << 'EOF'
# User Validation Module

A simple user validation library.

## Features
- Email validation
- Username validation  
- Password strength checking

## Usage
```python
from user_validator import validate_user

result, errors = validate_user({
    'email': 'user@example.com',
    'username': 'johndoe',
    'password': 'securepass123'
})
```
EOF

git add .
git commit -m "Initial commit: User validation module"

# Add more commits
cat > config.py << 'EOF'
"""
Configuration settings.
"""

# Validation settings
MIN_USERNAME_LENGTH = 3
MAX_USERNAME_LENGTH = 20
MIN_PASSWORD_LENGTH = 8

# Email settings
ALLOWED_EMAIL_DOMAINS = None  # None means all domains allowed

# Feature flags
ENABLE_STRICT_VALIDATION = False
EOF

git add config.py
git commit -m "Add configuration module"

# Create feature branch
git checkout -b feature/user-validation

# Make changes on feature branch
cat > user_validator.py << 'EOF'
"""
User validation module for the application.
Enhanced with additional validation rules.
"""

import re
from config import (
    MIN_USERNAME_LENGTH, 
    MAX_USERNAME_LENGTH,
    MIN_PASSWORD_LENGTH,
    ENABLE_STRICT_VALIDATION
)


def validate_email(email):
    """Validate email format."""
    if not email:
        return False
    pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
    return bool(re.match(pattern, email))


def validate_username(username):
    """Validate username format."""
    if not username:
        return False
    if len(username) < MIN_USERNAME_LENGTH:
        return False
    if len(username) > MAX_USERNAME_LENGTH:
        return False
    # Allow underscores in addition to alphanumeric
    if not re.match(r'^[a-zA-Z0-9_]+$', username):
        return False
    return True


def validate_password(password):
    """Validate password strength."""
    if not password:
        return False
    if len(password) < MIN_PASSWORD_LENGTH:
        return False
    
    if ENABLE_STRICT_VALIDATION:
        # Require at least one uppercase, lowercase, and digit
        if not re.search(r'[A-Z]', password):
            return False
        if not re.search(r'[a-z]', password):
            return False
        if not re.search(r'[0-9]', password):
            return False
    
    return True


def validate_phone(phone):
    """Validate phone number format."""
    if not phone:
        return True  # Phone is optional
    # Remove common separators
    cleaned = re.sub(r'[\s\-\(\)]', '', phone)
    # Check if it's a valid phone number (10-15 digits)
    return bool(re.match(r'^\+?[0-9]{10,15}$', cleaned))


def validate_user(user_data):
    """Validate complete user data."""
    errors = []
    
    if not validate_email(user_data.get('email', '')):
        errors.append('Invalid email format')
    
    if not validate_username(user_data.get('username', '')):
        errors.append('Invalid username')
    
    if not validate_password(user_data.get('password', '')):
        errors.append('Password too weak')
    
    if not validate_phone(user_data.get('phone', '')):
        errors.append('Invalid phone number')
    
    return len(errors) == 0, errors
EOF

git add user_validator.py
git commit -m "Enhance validation with config and phone support"

# Add tests on feature branch
cat > test_validator.py << 'EOF'
"""
Tests for user validation module.
"""

import pytest
from user_validator import (
    validate_email,
    validate_username,
    validate_password,
    validate_phone,
    validate_user
)


class TestEmailValidation:
    def test_valid_email(self):
        assert validate_email('user@example.com') is True
    
    def test_invalid_email_no_at(self):
        assert validate_email('userexample.com') is False
    
    def test_empty_email(self):
        assert validate_email('') is False


class TestUsernameValidation:
    def test_valid_username(self):
        assert validate_username('johndoe') is True
    
    def test_username_with_underscore(self):
        assert validate_username('john_doe') is True
    
    def test_too_short(self):
        assert validate_username('ab') is False


class TestPasswordValidation:
    def test_valid_password(self):
        assert validate_password('securepass123') is True
    
    def test_too_short(self):
        assert validate_password('short') is False
EOF

git add test_validator.py
git commit -m "Add unit tests for validators"

# Go back to main and make a conflicting change
git checkout main

# Make a change that will conflict
cat > user_validator.py << 'EOF'
"""
User validation module for the application.
Updated with better error messages.
"""

import re


def validate_email(email):
    """
    Validate email format.
    
    Args:
        email: Email address to validate
        
    Returns:
        bool: True if valid, False otherwise
    """
    if not email:
        return False
    pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
    return bool(re.match(pattern, email))


def validate_username(username):
    """
    Validate username format.
    
    Requirements:
    - Between 3 and 20 characters
    - Alphanumeric only
    """
    if not username:
        return False
    if len(username) < 3:
        return False
    if len(username) > 20:
        return False
    return username.isalnum()


def validate_password(password):
    """
    Validate password strength.
    
    Requirements:
    - At least 8 characters
    """
    if not password:
        return False
    if len(password) < 8:
        return False
    return True


def validate_user(user_data):
    """
    Validate complete user data.
    
    Args:
        user_data: Dictionary with user information
        
    Returns:
        tuple: (is_valid, list of errors)
    """
    errors = []
    
    if not validate_email(user_data.get('email', '')):
        errors.append('Invalid email: must be a valid email address')
    
    if not validate_username(user_data.get('username', '')):
        errors.append('Invalid username: must be 3-20 alphanumeric characters')
    
    if not validate_password(user_data.get('password', '')):
        errors.append('Invalid password: must be at least 8 characters')
    
    return len(errors) == 0, errors
EOF

git add user_validator.py
git commit -m "Improve docstrings and error messages"

echo ""
echo "Git repository initialized successfully!"
echo "Branches: main, feature/user-validation"
echo "A merge conflict will occur when merging feature/user-validation into main"
