# -*- coding: utf-8 -*-
"""
域名: agent.cdnlin.xyz
功能: 静态文件服务器
端口: 5003
"""

from flask import Flask, send_file, abort, request
import logging
import os

app = Flask(__name__)

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s [agent.cdnlin.xyz] %(message)s'
)


@app.route('/<path:filepath>')
def serve_file(filepath):
    """直接返回请求的文件（支持任意目录结构）"""
    app.logger.info(f"📥 请求: /{filepath}")
    app.logger.info(f"   IP: {request.remote_addr}")
    
    # 检查文件是否存在
    if os.path.exists(filepath) and os.path.isfile(filepath):
        file_size = os.path.getsize(filepath)
        file_size_mb = file_size / 1024 / 1024
        app.logger.info(f"   ✅ 返回文件 ({file_size_mb:.2f} MB)")
        return send_file(filepath, as_attachment=True)
    else:
        app.logger.warning(f"   ❌ 文件不存在")
        abort(404)


@app.route('/')
def index():
    """首页 - 显示文件列表"""
    
    def scan_directory(base_dir='.', prefix=''):
        """递归扫描目录"""
        html_parts = []
        
        try:
            items = sorted(os.listdir(base_dir))
        except:
            return ''
        
        for item in items:
            # 跳过系统文件和Python缓存
            if item.startswith('.') or item in ['__pycache__', 'venv']:
                continue
            
            full_path = os.path.join(base_dir, item)
            display_path = os.path.join(prefix, item) if prefix else item
            
            if os.path.isdir(full_path):
                html_parts.append(f"<li>📁 <b>{item}/</b></li>")
                html_parts.append(scan_directory(full_path, display_path))
            elif os.path.isfile(full_path):
                size = os.path.getsize(full_path)
                size_mb = size / 1024 / 1024
                url = f"/{display_path}".replace('\\', '/')
                html_parts.append(
                    f"<li>📄 <a href='{url}' style='color:#4ec9b0;'>{item}</a> "
                    f"<span style='color:#888;'>({size_mb:.2f} MB)</span></li>"
                )
        
        return '\n'.join(html_parts)
    
    files_html = scan_directory()
    
    return f"""
    <html>
    <head>
        <title>agent.cdnlin.xyz - 文件服务器</title>
        <style>
            body {{ 
                font-family: monospace; 
                padding: 20px; 
                background: #1e1e1e; 
                color: #dcdcaa; 
            }}
            a {{ text-decoration: none; }}
            a:hover {{ text-decoration: underline; }}
            ul {{ line-height: 1.8; }}
        </style>
    </head>
    <body>
        <h1>📦 agent.cdnlin.xyz</h1>
        <h3>静态文件服务器</h3>
        <hr>
        <h4>📂 可用文件:</h4>
        <ul>
            {files_html}
        </ul>
        <hr>
        <p style="color: #888; font-size:12px;">
            访问格式: /目录/文件名<br>
            示例: /cdnfly/python2.7-debian-12.tar.gz
        </p>
    </body>
    </html>
    """


@app.errorhandler(404)
def not_found(e):
    """404错误处理"""
    return f"""
    <html>
    <head><title>404 - 文件不存在</title></head>
    <body style="font-family: monospace; padding: 20px; background: #1e1e1e; color: #dcdcaa;">
        <h1>❌ 404 - 文件不存在</h1>
        <p>请求的文件不存在</p>
        <a href="/" style="color: #4ec9b0;">返回首页</a>
    </body>
    </html>
    """, 404


if __name__ == '__main__':
    print("="*60)
    print("  📦 agent.cdnlin.xyz 静态文件服务器")
    print("="*60)
    print("  监听: 0.0.0.0:5003")
    print("  功能: 直接返回文件")
    print("="*60)
    
    app.run(host='0.0.0.0', port=5003, debug=True)
