package com.example.myapplication.service;

import android.content.Context;
import android.util.Log;

import com.example.myapplication.domain.Chapter;
import com.example.myapplication.domain.Course;
import com.example.myapplication.repository.CourseRepository;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 数据初始化器 - 负责加载课程大纲数据到数据库
 */
public class DataInitializer {
    private static final String TAG = "DataInitializer";
    private final Context context;
    private final CourseRepository courseRepository;
    
    // 课程大纲文件列表
    private static final String[] COURSE_OUTLINE_FILES = {};
    
    public DataInitializer(Context context) {
        this.context = context.getApplicationContext();
        this.courseRepository = new CourseRepository(context);
    }
    
    /**
     * 初始化所有课程数据
     */
    public void initializeAllCourses() {
        Log.i(TAG, "开始初始化课程数据...");
        
        try {
            courseRepository.openDatabase();
            
            // 检查是否已有课程数据
            List<Course> existingCourses = courseRepository.getAllCourses();
            if (!existingCourses.isEmpty()) {
                Log.i(TAG, "数据库中已有课程数据，跳过初始化");
                return;
            }
            
            // 兼容现有数据库：不再从assets加载，直接返回
            
            Log.i(TAG, "课程数据初始化完成");
            
        } catch (Exception e) {
            Log.e(TAG, "初始化课程数据失败", e);
        } finally {
            courseRepository.closeDatabase();
        }
    }
    
    /**
     * 从assets加载课程数据
     */
    private void loadCourseFromAssets(String fileName) throws Exception { }
    
    /**
     * 解析课程基本信息
     */
    private Course parseCourse(JSONObject jsonObject) throws Exception {
        String courseId = jsonObject.optString("id");
        String courseTitle = jsonObject.optString("title");
        
        if (courseId.isEmpty() || courseTitle.isEmpty()) {
            // 尝试其他字段名
            courseId = jsonObject.optString("courseId");
            courseTitle = jsonObject.optString("courseTitle");
        }
        
        if (courseId.isEmpty() || courseTitle.isEmpty()) {
            return null;
        }
        
        Course course = new Course();
        course.setId(Integer.parseInt(courseId.replaceAll("\\D", "")));
        course.setName(courseTitle);
        course.setCode(courseId);
        course.setDescription(jsonObject.optString("description", ""));
        
        return course;
    }
    
    /**
     * 解析章节信息
     */
    private List<Chapter> parseChapters(JSONObject jsonObject, int courseId) throws Exception {
        List<Chapter> chapters = new ArrayList<>();
        
        JSONArray nodesArray = jsonObject.optJSONArray("nodes");
        if (nodesArray == null) {
            nodesArray = jsonObject.optJSONArray("children");
        }
        
        if (nodesArray != null) {
            for (int i = 0; i < nodesArray.length(); i++) {
                JSONObject node = nodesArray.getJSONObject(i);
                parseChapterNode(node, courseId, chapters, 0);
            }
        }
        
        return chapters;
    }
    
    /**
     * 递归解析章节节点
     */
    private void parseChapterNode(JSONObject node, int courseId, List<Chapter> chapters, int level) throws Exception {
        String chapterId = node.optString("id");
        String title = node.optString("title");
        
        if (!chapterId.isEmpty() && !title.isEmpty()) {
            Chapter chapter = new Chapter();
            chapter.setId(Integer.parseInt(chapterId.replaceAll("\\D", "")));
            chapter.setName(title);
            chapter.setCourseId(courseId);
            chapter.setOrderIndex(chapters.size() + 1);
            
            // 设置关键词
            JSONArray keywordsArray = node.optJSONArray("keywords");
            if (keywordsArray != null && keywordsArray.length() > 0) {
                StringBuilder keywords = new StringBuilder();
                for (int i = 0; i < keywordsArray.length(); i++) {
                    if (i > 0) keywords.append(",");
                    keywords.append(keywordsArray.getString(i));
                }
                chapter.setKeywords(keywords.toString());
            }
            
            // 设置别名
            JSONArray aliasesArray = node.optJSONArray("aliases");
            if (aliasesArray != null && aliasesArray.length() > 0) {
                StringBuilder aliases = new StringBuilder();
                for (int i = 0; i < aliasesArray.length(); i++) {
                    if (i > 0) aliases.append(",");
                    aliases.append(aliasesArray.getString(i));
                }
                chapter.setAliases(aliases.toString());
            }
            
            chapters.add(chapter);
        }
        
        // 递归处理子节点
        JSONArray childrenArray = node.optJSONArray("children");
        if (childrenArray != null) {
            for (int i = 0; i < childrenArray.length(); i++) {
                JSONObject childNode = childrenArray.getJSONObject(i);
                parseChapterNode(childNode, courseId, chapters, level + 1);
            }
        }
    }
}