from flask import Blueprint, request, jsonify, send_file
from src.models.user import db, User
from src.models.download import DownloadFile, DownloadLog
import os

download_bp = Blueprint('download', __name__)

@download_bp.route('/download/files', methods=['GET'])
def get_download_files():
    """다운로드 파일 목록 조회"""
    try:
        file_type = request.args.get('file_type')  # installer, manual, update
        
        query = DownloadFile.query.filter_by(is_active=True)
        if file_type:
            query = query.filter_by(file_type=file_type)
        
        files = query.order_by(DownloadFile.created_at.desc()).all()
        return jsonify([file.to_dict() for file in files])
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@download_bp.route('/download/files/latest', methods=['GET'])
def get_latest_files():
    """최신 파일 조회"""
    try:
        file_type = request.args.get('file_type')
        
        query = DownloadFile.query.filter_by(is_active=True, is_latest=True)
        if file_type:
            query = query.filter_by(file_type=file_type)
        
        files = query.all()
        return jsonify([file.to_dict() for file in files])
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@download_bp.route('/download/files', methods=['POST'])
def upload_file():
    """파일 업로드 (관리자용)"""
    try:
        data = request.get_json()
        
        required_fields = ['name', 'file_type', 'version', 'file_path', 'file_size']
        for field in required_fields:
            if field not in data:
                return jsonify({'error': f'{field} is required'}), 400
        
        # 같은 타입의 기존 최신 파일들을 최신이 아니도록 변경
        if data.get('is_latest', False):
            DownloadFile.query.filter_by(
                file_type=data['file_type'],
                is_latest=True
            ).update({'is_latest': False})
        
        file = DownloadFile(
            name=data['name'],
            description=data.get('description'),
            file_type=data['file_type'],
            version=data['version'],
            file_path=data['file_path'],
            file_size=data['file_size'],
            is_latest=data.get('is_latest', False)
        )
        
        db.session.add(file)
        db.session.commit()
        
        return jsonify(file.to_dict()), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@download_bp.route('/download/files/<int:file_id>', methods=['GET'])
def download_file(file_id):
    """파일 다운로드"""
    try:
        file = DownloadFile.query.get_or_404(file_id)
        
        if not file.is_active:
            return jsonify({'error': 'File is not available'}), 404
        
        # 다운로드 로그 기록
        user_id = request.args.get('user_id', type=int)
        ip_address = request.remote_addr
        user_agent = request.headers.get('User-Agent')
        
        log = DownloadLog(
            file_id=file_id,
            user_id=user_id,
            ip_address=ip_address,
            user_agent=user_agent
        )
        db.session.add(log)
        
        # 다운로드 카운트 증가
        file.download_count += 1
        db.session.commit()
        
        # 실제 파일 전송 (실제 구현에서는 파일 경로 확인 필요)
        if os.path.exists(file.file_path):
            return send_file(file.file_path, as_attachment=True, download_name=file.name)
        else:
            return jsonify({'error': 'File not found on server'}), 404
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@download_bp.route('/download/files/<int:file_id>/info', methods=['GET'])
def get_file_info(file_id):
    """파일 정보 조회"""
    try:
        file = DownloadFile.query.get_or_404(file_id)
        return jsonify(file.to_dict())
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@download_bp.route('/download/files/<int:file_id>', methods=['PUT'])
def update_file(file_id):
    """파일 정보 수정 (관리자용)"""
    try:
        file = DownloadFile.query.get_or_404(file_id)
        data = request.get_json()
        
        # 수정 가능한 필드
        updatable_fields = ['name', 'description', 'is_latest', 'is_active']
        for field in updatable_fields:
            if field in data:
                setattr(file, field, data[field])
        
        # 최신 파일로 설정하는 경우 다른 파일들의 최신 상태 해제
        if data.get('is_latest', False):
            DownloadFile.query.filter(
                DownloadFile.file_type == file.file_type,
                DownloadFile.id != file_id
            ).update({'is_latest': False})
        
        db.session.commit()
        return jsonify(file.to_dict())
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@download_bp.route('/download/files/<int:file_id>', methods=['DELETE'])
def delete_file(file_id):
    """파일 삭제 (관리자용)"""
    try:
        file = DownloadFile.query.get_or_404(file_id)
        
        # 실제 파일 삭제 (선택사항)
        # if os.path.exists(file.file_path):
        #     os.remove(file.file_path)
        
        db.session.delete(file)
        db.session.commit()
        
        return jsonify({'message': 'File deleted successfully'})
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@download_bp.route('/download/stats', methods=['GET'])
def get_download_stats():
    """다운로드 통계"""
    try:
        file_type = request.args.get('file_type')
        
        query = DownloadFile.query.filter_by(is_active=True)
        if file_type:
            query = query.filter_by(file_type=file_type)
        
        files = query.all()
        
        stats = {
            'total_files': len(files),
            'total_downloads': sum(file.download_count for file in files),
            'files': [
                {
                    'name': file.name,
                    'version': file.version,
                    'download_count': file.download_count,
                    'file_type': file.file_type
                }
                for file in files
            ]
        }
        
        return jsonify(stats)
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@download_bp.route('/download/file-types', methods=['GET'])
def get_file_types():
    """파일 타입 목록"""
    file_types = [
        {'id': 'installer', 'name': '설치 파일'},
        {'id': 'manual', 'name': '매뉴얼'},
        {'id': 'update', 'name': '업데이트'}
    ]
    return jsonify(file_types)

