#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Document Translator Flask 應用程式入口

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

import os
import sys
from pathlib import Path
from datetime import datetime

# 添加專案根目錄到 Python 路徑
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

from app import create_app, db
from app.models import User, TranslationJob, JobFile, TranslationCache, APIUsageStats, SystemLog

# 創建 Flask 應用
app = create_app()

# 導出 Celery 實例供 worker 使用
celery = app.celery

# 確保在模組級別可以訪問
__all__ = ['app', 'celery']


@app.shell_context_processor
def make_shell_context():
    """為 Flask shell 提供上下文"""
    return {
        'db': db,
        'User': User,
        'TranslationJob': TranslationJob,
        'JobFile': JobFile,
        'TranslationCache': TranslationCache,
        'APIUsageStats': APIUsageStats,
        'SystemLog': SystemLog
    }


@app.cli.command()
def init_db():
    """初始化資料庫"""
    click.echo('Initializing database...')
    db.create_all()
    click.echo('Database initialized.')


@app.cli.command()
def test():
    """運行測試"""
    import unittest
    tests = unittest.TestLoader().discover('tests')
    unittest.TextTestRunner(verbosity=2).run(tests)


@app.route('/')
def index():
    """首頁路由"""
    return {
        'application': 'PANJIT Document Translator',
        'version': '1.0.0',
        'status': 'running',
        'api_base_url': '/api/v1'
    }


@app.route('/api')
def api_info():
    """API 資訊"""
    return {
        'api_version': 'v1',
        'base_url': '/api/v1',
        'endpoints': {
            'auth': '/api/v1/auth',
            'files': '/api/v1/files',
            'jobs': '/api/v1/jobs',
            'admin': '/api/v1/admin',
            'health': '/api/v1/health'
        },
        'documentation': 'Available endpoints provide RESTful API for document translation'
    }


@app.route('/api/health')
@app.route('/api/v1/health')
def health_check():
    """健康檢查端點"""
    return {
        'status': 'healthy',
        'timestamp': datetime.utcnow().isoformat(),
        'service': 'PANJIT Document Translator API',
        'version': '1.0.0'
    }, 200


if __name__ == '__main__':
    # 檢查環境變數
    port = int(os.environ.get('PORT', 5000))
    debug = os.environ.get('FLASK_DEBUG', 'false').lower() == 'true'
    host = os.environ.get('HOST', '127.0.0.1')
    
    # 只在主進程或非 debug 模式下顯示啟動訊息
    # 在 debug 模式下，Flask 會創建兩個進程，只在 reloader 主進程顯示訊息
    if not debug or os.environ.get('WERKZEUG_RUN_MAIN'):
        print(f"""
    PANJIT Document Translator Starting...
    
    Server: http://{host}:{port}
    Debug Mode: {debug}
    API Documentation: http://{host}:{port}/api
    Health Check: http://{host}:{port}/api/v1/health
    
    Upload Directory: {app.config.get('UPLOAD_FOLDER')}
    Database: {app.config.get('SQLALCHEMY_DATABASE_URI', '').split('/')[-1]}
    SMTP: {app.config.get('SMTP_SERVER')}
    LDAP: {app.config.get('LDAP_SERVER')}
    
    Press Ctrl+C to stop the server.
        """)
    
    # 啟動應用
    try:
        app.run(
            host=host,
            port=port,
            debug=debug,
            use_reloader=debug
        )
    except KeyboardInterrupt:
        if not debug or os.environ.get('WERKZEUG_RUN_MAIN'):
            print("\nServer stopped by user.")
    except Exception as e:
        if not debug or os.environ.get('WERKZEUG_RUN_MAIN'):
            print(f"\nServer failed to start: {str(e)}")
        sys.exit(1)