#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
pytest 配置和 fixtures

Author: PANJIT IT Team
Created: 2024-01-28
Modified: 2024-01-28
"""

import pytest
import tempfile
import os
from pathlib import Path
from app import create_app, db
from app.models.user import User
from app.models.job import TranslationJob


@pytest.fixture(scope='session')
def app():
    """建立測試應用程式"""
    # 建立臨時資料庫
    db_fd, db_path = tempfile.mkstemp()
    
    # 測試配置
    test_config = {
        'TESTING': True,
        'SQLALCHEMY_DATABASE_URI': f'sqlite:///{db_path}',
        'WTF_CSRF_ENABLED': False,
        'SECRET_KEY': 'test-secret-key',
        'UPLOAD_FOLDER': tempfile.mkdtemp(),
        'MAX_CONTENT_LENGTH': 26214400,
        'SMTP_SERVER': 'localhost',
        'SMTP_PORT': 25,
        'SMTP_SENDER_EMAIL': 'test@example.com',
        'LDAP_SERVER': 'localhost',
        'LDAP_PORT': 389,
        'LDAP_BIND_USER_DN': 'test',
        'LDAP_BIND_USER_PASSWORD': 'test',
        'LDAP_SEARCH_BASE': 'dc=test',
        'REDIS_URL': 'redis://localhost:6379/15'  # 使用測試資料庫
    }
    
    app = create_app('testing')
    
    # 覆蓋測試配置
    for key, value in test_config.items():
        app.config[key] = value
    
    with app.app_context():
        db.create_all()
        yield app
        db.drop_all()
    
    os.close(db_fd)
    os.unlink(db_path)


@pytest.fixture
def client(app):
    """建立測試客戶端"""
    return app.test_client()


@pytest.fixture
def runner(app):
    """建立 CLI 測試執行器"""
    return app.test_cli_runner()


@pytest.fixture
def auth_user(app):
    """建立測試使用者"""
    with app.app_context():
        user = User(
            username='testuser',
            display_name='Test User',
            email='test@panjit.com.tw',
            department='IT',
            is_admin=False
        )
        db.session.add(user)
        db.session.commit()
        return user


@pytest.fixture
def admin_user(app):
    """建立管理員使用者"""
    with app.app_context():
        admin = User(
            username='admin',
            display_name='Admin User',
            email='admin@panjit.com.tw',
            department='IT',
            is_admin=True
        )
        db.session.add(admin)
        db.session.commit()
        return admin


@pytest.fixture
def sample_job(app, auth_user):
    """建立測試翻譯任務"""
    with app.app_context():
        job = TranslationJob(
            user_id=auth_user.id,
            original_filename='test.docx',
            file_extension='.docx',
            file_size=1024,
            file_path='/tmp/test.docx',
            source_language='auto',
            target_languages=['en', 'vi'],
            status='PENDING'
        )
        db.session.add(job)
        db.session.commit()
        return job


@pytest.fixture
def authenticated_client(client, auth_user):
    """已認證的測試客戶端"""
    with client.session_transaction() as sess:
        sess['user_id'] = auth_user.id
        sess['username'] = auth_user.username
        sess['is_admin'] = auth_user.is_admin
    
    return client


@pytest.fixture
def admin_client(client, admin_user):
    """管理員測試客戶端"""
    with client.session_transaction() as sess:
        sess['user_id'] = admin_user.id
        sess['username'] = admin_user.username
        sess['is_admin'] = admin_user.is_admin
    
    return client


@pytest.fixture
def sample_file():
    """建立測試檔案"""
    import io
    
    # 建立假的 DOCX 檔案內容
    file_content = b"Mock DOCX file content for testing"
    
    return io.BytesIO(file_content)


@pytest.fixture
def mock_dify_response():
    """模擬 Dify API 回應"""
    return {
        'answer': 'This is a translated text.',
        'metadata': {
            'usage': {
                'prompt_tokens': 10,
                'completion_tokens': 5,
                'total_tokens': 15,
                'prompt_unit_price': 0.0001,
                'prompt_price_unit': 'USD'
            }
        }
    }


@pytest.fixture
def mock_ldap_response():
    """模擬 LDAP 認證回應"""
    return {
        'username': 'testuser',
        'display_name': 'Test User',
        'email': 'test@panjit.com.tw',
        'department': 'IT',
        'user_principal_name': 'testuser@panjit.com.tw'
    }