import datetime
import os
import time
from django.db import transaction
from apps.content.models import Tag
from django.conf import settings
from django.db import IntegrityError
import re
from apps.log_service.services import log_service  # 引入你的日志服务


def import_tag(batch_size):
    # 为每次导入生成唯一的task_id，包含时间戳，确保日志独立
    task_id = f"tag_import"
    log_service.clear(task_id)
    log_service.write_log(task_id, '开始安全批量导入标签（带进度显示）', log_type='track')

    try:
        # 先导出当前所有标签
        log_service.write_log(task_id, '正在导出当前所有标签...', log_type='track')
        tags = Tag.objects.values_list('title', flat=True)
        timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
        export_file = f'{settings.BASE_DIR}/static/tag_words/tag_word_out_{timestamp}.txt'
        os.makedirs(os.path.dirname(export_file), exist_ok=True)

        with open(export_file, 'w', encoding='utf-8') as f:
            f.write('\n'.join(tags))

        log_service.write_log(task_id,
                              f'已导出{len(tags)}个现有标签到{export_file}',
                              log_type='track')

        # 处理源文件
        file_path = f'{settings.BASE_DIR}/static/tag_words/tag_words.txt'
        if not os.path.exists(file_path):
            error_msg = "“/static/tag_words/tag_words.txt”文件不存在"
            log_service.write_log(task_id,
                                  f'错误: {error_msg}',
                                  log_type='track')
            raise FileNotFoundError(error_msg)

        # 读取并去重（同时处理existing_tags和自身重复）
        log_service.write_log(task_id, '正在读取源文件并去重...', log_type='track')
        with open(file_path, 'r', encoding='utf-8') as f:
            seen = set(tags)  # 初始化已存在标签集合
            new_lines = []
            for line in f:
                line = line.strip()
                if line and line not in seen:
                    seen.add(line)
                    new_lines.append(line)
            total_lines = len(new_lines)

        log_service.write_log(task_id,
                              f'去重完成，共有{total_lines}个新标签需要导入',
                              log_type='track')

        # 写入去重后的内容
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write('\n'.join(new_lines) + '\n')

        processed = 0
        start_time = time.time()
        # 移除了 last_log_time，因为我们希望每次循环都记录

        for iteration in range(9999999):
            with open(file_path, 'r+', encoding='utf-8') as f:
                lines = f.readlines()
                remaining = len(lines)

                if remaining == 0:
                    completion_msg = f'已完成所有处理，共导入{processed}个标签'
                    log_service.write_log(task_id,
                                          completion_msg,
                                          log_type='track')
                    break

                # 处理当前批次
                batch_lines = lines[:batch_size]
                batch = [
                    Tag(title=line.strip(), status=99) for line in batch_lines
                    if line.strip()
                ]

                if batch:
                    try:
                        with transaction.atomic():
                            Tag.objects.bulk_create(batch)
                        processed += len(batch)

                        # 立即记录当前批次进度，移除时间间隔检查
                        progress_percent = min(100,
                                               100 * processed / total_lines)
                        log_service.write_log(
                            task_id,
                            f'批次{iteration+1}: 已处理{processed}/{total_lines}个标签 '
                            f'({progress_percent:.1f}%)',  # 批次号从1开始
                            log_type='track')  # 移除了 last_log_time 的更新

                    except IntegrityError as e:
                        # 捕获完整性错误
                        error_msg = str(e)
                        match = re.search(r"Duplicate entry '(.+?)' for key",
                                          error_msg)
                        if match:
                            duplicate_title = match.group(1)
                            warning_msg = f"检测到重复标题，正在移除: '{duplicate_title}'"
                            log_service.write_log(task_id,
                                                  warning_msg,
                                                  log_type='track')
                            # 从文件队列中移除此重复项
                            lines = [
                                line for line in lines
                                if line.strip() != duplicate_title
                            ]
                            # 重置文件指针并写入更新后的内容
                            f.seek(0)
                            f.truncate()
                            f.writelines(lines)
                            continue
                        else:
                            error_msg = f"数据库完整性错误: {error_msg}"
                            log_service.write_log(task_id,
                                                  error_msg,
                                                  log_type='track')
                            raise e

                # 更新文件内容
                f.seek(0)
                f.truncate()
                f.writelines(lines[batch_size:])

                # 每完成10%记录一次详细进度（可选，根据需要保留）
                if processed > 0 and processed % max(1,
                                                     total_lines // 10) == 0:
                    progress_percent = min(100, 100 * processed / total_lines)
                    elapsed_time = time.time() - start_time
                    items_per_second = processed / elapsed_time if elapsed_time > 0 else 0
                    log_service.write_log(task_id,
                                          f'进度: {progress_percent:.1f}% | '
                                          f'已处理: {processed}/{total_lines} | '
                                          f'速度: {items_per_second:.2f} 条/秒 | '
                                          f'用时: {elapsed_time:.2f}秒',
                                          log_type='track')

        # 最终完成日志
        end_time = time.time()
        total_time = end_time - start_time
        log_service.write_log(task_id, f'导入任务完成! '
                              f'总计: {processed}个标签 | '
                              f'用时: {total_time:.2f}秒 | '
                              f'平均速度: {processed/total_time:.2f} 条/秒',
                              log_type='track')
        # 批量创建后，手动清除缓存
        Tag._clear_total_count_cache()
        return {
            'total': processed,
            'time': round(total_time, 2),
            'exported': len(tags),
            'export_file': export_file,
            'task_id': task_id  # 返回唯一的任务ID供前端查看日志
        }

    except Exception as e:
        error_msg = f'处理失败: {str(e)}'
        log_service.write_log(task_id, error_msg, log_type='track')
        log_service.write_log(task_id,
                              f'错误类型: {type(e).__name__}',
                              log_type='track')
        raise
