#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
文件删除API服务
用于处理个人主页的文件删除请求
"""

import http.server
import socketserver
import json
import os
import sys
import cgi

PORT = 3002
BASE_DIR = "/var/www/html/internal/users"

class DeleteHandler(http.server.BaseHTTPRequestHandler):
    def do_OPTIONS(self):
        self.send_response(200)
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type')
        self.end_headers()
    
    def do_POST(self):
        if self.path == '/delete-user-file':
            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length)
            
            try:
                data = json.loads(post_data.decode('utf-8'))
                folder = data.get('folder', '')
                filename = data.get('filename', '')
                
                # 安全检查
                if '..' in filename or '/' in filename:
                    self.send_error_response('非法文件名')
                    return
                
                if '..' in folder or folder.startswith('/'):
                    self.send_error_response('非法文件夹')
                    return
                
                file_path = os.path.join(BASE_DIR, folder, filename)
                
                # 检查文件是否存在
                if not os.path.exists(file_path):
                    self.send_error_response('文件不存在')
                    return
                
                # 删除文件
                os.remove(file_path)
                print(f"[删除成功] {file_path}")
                
                # 更新files.json
                self.update_files_json(folder, filename)
                
                self.send_success_response('文件已删除')
                
            except Exception as e:
                print(f"[删除失败] {e}")
                self.send_error_response(str(e))
        else:
            self.send_error_response('未知接口')
    
    def update_files_json(self, folder, deleted_filename):
        """更新files.json，移除已删除的文件"""
        try:
            files_json_path = os.path.join(BASE_DIR, folder, 'files.json')
            if os.path.exists(files_json_path):
                with open(files_json_path, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                
                # 过滤掉已删除的文件
                data['files'] = [item for item in data['files'] if item['file'] != deleted_filename]
                data['updated'] = __import__('datetime').datetime.now().isoformat()
                
                with open(files_json_path, 'w', encoding='utf-8') as f:
                    json.dump(data, f, ensure_ascii=False, indent=2)
                
                print(f"[已更新] {files_json_path}")
        except Exception as e:
            print(f"[更新files.json失败] {e}")
    
    def send_success_response(self, message):
        self.send_response(200)
        self.send_header('Content-Type', 'application/json')
        self.send_header('Access-Control-Allow-Origin', '*')
        self.end_headers()
        response = {'success': True, 'message': message}
        self.wfile.write(json.dumps(response).encode('utf-8'))
    
    def send_error_response(self, error):
        self.send_response(200)  # 返回200但标记为失败
        self.send_header('Content-Type', 'application/json')
        self.send_header('Access-Control-Allow-Origin', '*')
        self.end_headers()
        response = {'success': False, 'error': error}
        self.wfile.write(json.dumps(response).encode('utf-8'))
    
    def log_message(self, format, *args):
        print(f"[{self.log_date_time_string()}] {format % args}")

if __name__ == '__main__':
    with socketserver.TCPServer(("127.0.0.1", PORT), DeleteHandler) as httpd:
        print(f"文件删除API服务已启动: http://127.0.0.1:{PORT}")
        print("接口: POST /delete-user-file")
        print("按 Ctrl+C 停止服务")
        httpd.serve_forever()
