import pytest
import os
import json
import shutil
from app import create_app

@pytest.fixture
def app():
    """Create a Flask application instance for testing."""
    # Test configuration
    test_config = {
        'TESTING': True,
        'STORAGE_PATH': 'test_storage',
        'SECRET_KEY': 'test_key',
        'WTF_CSRF_ENABLED': False
    }
    
    # Create test storage directory
    if not os.path.exists('test_storage'):
        os.makedirs('test_storage')
    
    # Create basic directory structure
    for dir_name in ['users', 'schemas', 'filetypes', 'projects', 'logs', 'exports']:
        if not os.path.exists(f'test_storage/{dir_name}'):
            os.makedirs(f'test_storage/{dir_name}')
    
    # Create app with test configuration
    app = create_app('testing')
    
    # Create context
    with app.app_context():
        # Set up test data
        initialize_test_data()
        
    yield app
    
    # Clean up after tests
    shutil.rmtree('test_storage', ignore_errors=True)

@pytest.fixture
def client(app):
    """Create a test client for the application."""
    return app.test_client()

@pytest.fixture
def auth(client):
    """Helper for authentication tests."""
    class AuthActions:
        def login(self, username='admin', password='admin123'):
            return client.post('/auth/login', data={
                'username': username,
                'password': password
            }, follow_redirects=True)
            
        def logout(self):
            return client.get('/auth/logout', follow_redirects=True)
            
    return AuthActions()

@pytest.fixture
def logged_in_client(client, auth):
    """Client that's already logged in as admin."""
    auth.login()
    return client

def initialize_test_data():
    """Initialize test data files."""
    # Create test users
    users_data = {
        "admin": {
            "nombre": "Administrador",
            "username": "admin",
            "email": "admin@ejemplo.com",
            "password_hash": "$2b$12$Q5Nz3QSF0FP.mKAxPmWXmurKn1oor4Cl1KbYZAKsFbGcEWWyPHou6",  # admin123
            "nivel": 9999,
            "idioma": "es",
            "fecha_caducidad": None,
            "empresa": "ARCH",
            "estado": "activo"
        },
        "user1": {
            "nombre": "Usuario Normal",
            "username": "user1",
            "email": "user1@ejemplo.com",
            "password_hash": "$2b$12$Q5Nz3QSF0FP.mKAxPmWXmurKn1oor4Cl1KbYZAKsFbGcEWWyPHou6",  # admin123
            "nivel": 1000,
            "idioma": "es",
            "fecha_caducidad": None,
            "empresa": "ARCH",
            "estado": "activo"
        }
    }
    
    with open('test_storage/users/users.json', 'w', encoding='utf-8') as f:
        json.dump(users_data, f, ensure_ascii=False, indent=2)
    
    # Create test file types
    filetypes_data = {
        "pdf": {
            "extension": "pdf",
            "descripcion": "Documento PDF",
            "mime_type": "application/pdf",
            "tamano_maximo": 20971520
        },
        "txt": {
            "extension": "txt",
            "descripcion": "Documento de texto",
            "mime_type": "text/plain",
            "tamano_maximo": 5242880
        }
    }
    
    with open('test_storage/filetypes/filetypes.json', 'w', encoding='utf-8') as f:
        json.dump(filetypes_data, f, ensure_ascii=False, indent=2)
    
    # Create test schemas
    schemas_data = {
        "TEST001": {
            "codigo": "TEST001",
            "descripcion": "Esquema de prueba",
            "fecha_creacion": "2023-10-01T10:00:00Z",
            "creado_por": "admin",
            "documentos": [
                {
                    "tipo": "pdf",
                    "nombre": "Documento de Prueba",
                    "nivel_ver": 0,
                    "nivel_editar": 1000
                }
            ]
        }
    }
    
    with open('test_storage/schemas/schema.json', 'w', encoding='utf-8') as f:
        json.dump(schemas_data, f, ensure_ascii=False, indent=2)
    
    # Create indices file
    indices_data = {
        "max_project_id": 0,
        "max_document_id": 0
    }
    
    with open('test_storage/indices.json', 'w', encoding='utf-8') as f:
        json.dump(indices_data, f, ensure_ascii=False, indent=2)
