"""Web interface for configuration management."""

import logging
from flask import Flask, render_template, request, jsonify, redirect, url_for
from .config import ConfigManager, RepositoryConfig

logger = logging.getLogger(__name__)

app = Flask(__name__)
config_manager = ConfigManager()


@app.route('/')
def index():
    """Main configuration page."""
    config = config_manager.load()
    return render_template('index.html', config=config)


@app.route('/api/config', methods=['GET'])
def get_config():
    """Get current configuration."""
    config = config_manager.load()
    return jsonify({
        'llm': {
            'api_url': config.llm.api_url,
            'api_key': config.llm.api_key[:10] + '...' if len(config.llm.api_key) > 10 else config.llm.api_key,
            'model': config.llm.model
        },
        'repositories': [
            {
                'name': repo.name,
                'branch': repo.branch,
                'webhook_url': repo.webhook_url[:30] + '...' if len(repo.webhook_url) > 30 else repo.webhook_url
            }
            for repo in config.repositories
        ],
        'schedule_time': config.schedule_time,
        'summary_dir': config.summary_dir
    })


@app.route('/api/llm', methods=['POST'])
def update_llm():
    """Update LLM configuration."""
    data = request.json
    
    try:
        config_manager.update_llm(
            api_url=data.get('api_url'),
            api_key=data.get('api_key'),
            model=data.get('model')
        )
        return jsonify({'success': True, 'message': 'LLM配置已更新'})
    except Exception as e:
        logger.error(f"Error updating LLM config: {e}")
        return jsonify({'success': False, 'message': str(e)}), 400


@app.route('/api/repository', methods=['POST'])
def add_repository():
    """Add a new repository configuration."""
    data = request.json
    
    try:
        config_manager.add_repository(
            name=data.get('name'),
            branch=data.get('branch'),
            webhook_url=data.get('webhook_url')
        )
        return jsonify({'success': True, 'message': '仓库配置已添加'})
    except Exception as e:
        logger.error(f"Error adding repository: {e}")
        return jsonify({'success': False, 'message': str(e)}), 400


@app.route('/api/repository', methods=['DELETE'])
def remove_repository():
    """Remove a repository configuration."""
    data = request.json
    
    try:
        config_manager.remove_repository(
            name=data.get('name'),
            branch=data.get('branch')
        )
        return jsonify({'success': True, 'message': '仓库配置已删除'})
    except Exception as e:
        logger.error(f"Error removing repository: {e}")
        return jsonify({'success': False, 'message': str(e)}), 400


@app.route('/api/config/full', methods=['POST'])
def update_full_config():
    """Update full configuration."""
    data = request.json
    
    try:
        config = config_manager.load()
        
        # Update LLM config
        if 'llm' in data:
            config.llm.api_url = data['llm'].get('api_url', config.llm.api_url)
            config.llm.api_key = data['llm'].get('api_key', config.llm.api_key)
            config.llm.model = data['llm'].get('model', config.llm.model)
        
        # Update repositories
        if 'repositories' in data:
            config.repositories = [
                RepositoryConfig(**repo) for repo in data['repositories']
            ]
        
        # Update other settings
        if 'schedule_time' in data:
            config.schedule_time = data['schedule_time']
        if 'summary_dir' in data:
            config.summary_dir = data['summary_dir']
        if 'github_token' in data:
            config.github_token = data['github_token']
        if 'timezone' in data:
            config.timezone = data['timezone']
        
        config_manager.save(config)
        return jsonify({'success': True, 'message': '配置已更新'})
    except Exception as e:
        logger.error(f"Error updating config: {e}")
        return jsonify({'success': False, 'message': str(e)}), 400


def run_server(host: str = '0.0.0.0', port: int = 5000, debug: bool = False):
    """Run the web server.
    
    Args:
        host: Host to bind to
        port: Port to listen on
        debug: Enable debug mode
    """
    app.run(host=host, port=port, debug=debug)


if __name__ == '__main__':
    # Note: Debug mode should not be used in production
    # Use environment variable to control debug mode
    import os
    debug_mode = os.environ.get('FLASK_DEBUG', 'False').lower() == 'true'
    run_server(debug=debug_mode)
