#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
根据 compressed_group_time_issues.json 的信息，将文件备份到 bak 目录
"""

import json
import shutil
from pathlib import Path


# 配置路径
JSON_FILE_PATH = 'server/jsons/compressed_group_time_issues.json'
CC_DIR = Path('cc')
BAK_DIR = Path('bak')


def find_subfolder(base_dir: Path, folder_name: str) -> Path | None:
    """
    在 base_dir 下查找名为 folder_name 的子文件夹
    """
    target = base_dir / folder_name
    if target.exists() and target.is_dir():
        return target
    return None


def find_21cnjy_folder(base_dir: Path) -> Path | None:
    """
    查找二一教育（21 世纪教育网）文件夹
    参照 association_detail.py 第 733-738 行的逻辑
    """
    candidates = [
        "21世纪教育网",
        "二一教育",
        "21世纪教育",
        "二一世纪教育"
    ]
    for candidate in candidates:
        folder = base_dir / candidate
        if folder.exists() and folder.is_dir():
            return folder
    return None


def find_zxxk_folder(base_dir: Path) -> Path | None:
    """
    查找学科网文件夹
    """
    return base_dir / "学科网"


def copy_file_with_path(src_file: Path, dst_dir: Path) -> None:
    """
    复制文件及其 2 级路径（source_folder 和 二一教育/学科网）到目标目录
    """
    if not src_file.exists():
        return

    source_folder_name = src_file.parent.parent.name
    platform_folder_name = src_file.parent.name

    # 构建目标路径：bak/source_folder/platform_folder/
    dst_file = dst_dir / source_folder_name / platform_folder_name / src_file.name

    # 创建目标目录
    dst_file.parent.mkdir(parents=True, exist_ok=True)

    # 复制文件
    shutil.copy2(str(src_file), str(dst_file))


def process_record(record: dict, cc_dir: Path, bak_dir: Path) -> dict:
    """
    处理一条记录，返回处理结果
    """
    result = {
        'row_index': record.get('row_index'),
        'source_folder': record.get('source_folder'),
        'group1_copied': False,
        'group2_copied': False,
        'group1_file': None,
        'group2_file': None,
        'error': None
    }

    source_folder_name = record.get('source_folder')
    if not source_folder_name:
        result['error'] = 'Missing source_folder'
        return result

    # 在 cc 目录下查找 source_folder
    source_dir = find_subfolder(cc_dir, source_folder_name)
    if not source_dir:
        result['error'] = f'Source folder not found: {source_folder_name}'
        return result

    # 查找二一教育和学科网文件夹
    group1_folder = find_21cnjy_folder(source_dir)
    group2_folder = find_zxxk_folder(source_dir)

    if not group2_folder:
        result['error'] = f'学科网 folder not found in {source_folder_name}'
        print(f"Warning: 学科网 folder not found in {source_folder_name}, skipping this record.")
        return result

    if not group1_folder:
        result['error'] = f'二一教育 folder not found in {source_folder_name}'
        print(f"Warning: 二一教育 folder not found in {source_folder_name}, skipping this record.")
        return result

    # 获取 group1 和 group2 的第一个文件（zip 文件）
    group1_files = record.get('group1', {}).get('files', [])
    group2_files = record.get('group2', {}).get('files', [])

    if not group1_files or not group2_files:
        result['error'] = 'Missing files in group1 or group2'
        return result

    group1_zip_name = group1_files[0].get('name')
    group2_zip_name = group2_files[0].get('name')

    # 构建源文件路径
    group1_src_file = group1_folder / group1_zip_name
    group2_src_file = group2_folder / group2_zip_name

    # 复制 group1 文件（二一教育）
    if group1_src_file.exists():
        copy_file_with_path(group1_src_file, bak_dir)
        result['group1_copied'] = True
        result['group1_file'] = group1_zip_name
    else:
        result['error'] = f'Group1 file not found: {group1_src_file}'
        return result

    # 复制 group2 文件（学科网）
    if group2_src_file.exists():
        copy_file_with_path(group2_src_file, bak_dir)
        result['group2_copied'] = True
        result['group2_file'] = group2_zip_name
    else:
        result['error'] = f'Group2 file not found: {group2_src_file}'
        return result

    return result


def main():
    """主函数"""
    print("=" * 60)
    print("开始备份文件到 bak 目录")
    print("=" * 60)

    # 加载 JSON 数据
    with open(JSON_FILE_PATH, 'r', encoding='utf-8') as f:
        data = json.load(f)

    print(f"共 {len(data)} 条记录需要处理\n")

    success_count = 0
    fail_count = 0

    for record in data:
        row_index = record.get('row_index', 'unknown')
        source_folder = record.get('source_folder', 'unknown')

        result = process_record(record, CC_DIR, BAK_DIR)

        if result['group1_copied'] and result['group2_copied']:
            success_count += 1
            print(f"✓ [{row_index}] {source_folder}")
            print(f"    二一教育：{result['group1_file']}")
            print(f"    学科网：{result['group2_file']}")
        else:
            fail_count += 1
            print(f"✗ [{row_index}] {source_folder}")
            print(f"    错误：{result['error']}")

    print("\n" + "=" * 60)
    print(f"备份完成！成功：{success_count} 条，失败：{fail_count} 条")
    print("=" * 60)


if __name__ == '__main__':
    main()
