package com.njcn.advance.event.cause.core;

import com.njcn.advance.event.cause.model.AnalysisResult;
import com.njcn.advance.event.cause.model.DataCause;
import com.njcn.advance.event.cause.model.DataFeature;
import com.njcn.advance.event.cause.model.QvvrDataStruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 电压暂降分析器主类
 * 对应C语言中的main_pro.c文件的cause_main_app函数
 */
public class VoltageSagAnalyzer {
    private static final Logger logger = LoggerFactory.getLogger(VoltageSagAnalyzer.class);

    private final FeatureCalculator featureCalculator;

    public VoltageSagAnalyzer() {
        this.featureCalculator = new FeatureCalculator();
    }

    /**
     * 主要分析函数 - 对应qvvr_fun_cause
     * @param qvvrData 输入的电压暂降数据结构
     * @return 处理结果，0表示成功，1表示失败
     */
    public int analyzeVoltageSag(QvvrDataStruct qvvrData) {
        long startTime = System.currentTimeMillis();

        try {
            logger.info("开始电压暂降分析，采样率={}，数据长度={}",
                    qvvrData.getSmpRate(), qvvrData.getSmpLen());

            // 参数校验
            if (!validateInput(qvvrData)) {
                qvvrData.setCause(0);
                qvvrData.setNoCal(1);
                return 1;
            }

            // 创建数据处理对象
            DataCause dataCause = createDataCause(qvvrData);
            DataFeature resultFeature = new DataFeature();

            // 特征值计算
            int ret = featureCalculator.calculateFeatures(dataCause, resultFeature);
            if (ret == 0) {
                // 阈值判断确定暂降原因
                int judgeStatus = ThresholdJudge.thresholdJudge(resultFeature);

                // 设置输出结果
                qvvrData.setCause(resultFeature.getCause());
                qvvrData.setNoCal(0);

                long processingTime = System.currentTimeMillis() - startTime;
                logger.info("分析完成，原因={} ({}), 处理时间={}ms, 判断状态={}",
                        resultFeature.getCause(),
                        ThresholdJudge.getCauseDescription(resultFeature.getCause()),
                        processingTime, judgeStatus);

                // 输出详细特征信息
                logFeatureDetails(resultFeature);

                return 0;
            } else {
                qvvrData.setCause(0);
                qvvrData.setNoCal(1);
                logger.error("特征计算失败");
                return 1;
            }

        } catch (Exception e) {
            logger.error("分析过程发生异常", e);
            qvvrData.setCause(0);
            qvvrData.setNoCal(1);
            return 1;
        }
    }

    /**
     * 输入参数校验
     * @param qvvrData 输入数据
     * @return true表示合法，false表示不合法
     */
    private boolean validateInput(QvvrDataStruct qvvrData) {
        // 首先判断数据个数和采样率是否合理
        if ((qvvrData.getSmpRate() > FeatureCalculator.MAX_SAMPLE_NUM) ||
                (qvvrData.getSmpRate() < FeatureCalculator.MIN_SAMPLE_NUM)) {
            logger.error("采样率超出范围: {}", qvvrData.getSmpRate());
            return false;
        }

        if (qvvrData.getSmpLen() > FeatureCalculator.MAX_DATA_LEN) {
            logger.error("数据长度超出范围: {}", qvvrData.getSmpLen());
            return false;
        }

        if (qvvrData.getSmpLen() <= 0) {
            logger.error("数据长度为空");
            return false;
        }

        return true;
    }

    /**
     * 创建数据处理对象
     * @param qvvrData 输入数据结构
     * @return 数据处理对象
     */
    private DataCause createDataCause(QvvrDataStruct qvvrData) {
        DataCause dataCause = new DataCause();

        dataCause.setSmp(qvvrData.getSmpRate());
        dataCause.setF(50.0f);  // 默认50Hz工频
        dataCause.setNum(qvvrData.getSmpLen());

        // 复制电压数据
        float[] va = new float[qvvrData.getSmpLen()];
        float[] vb = new float[qvvrData.getSmpLen()];
        float[] vc = new float[qvvrData.getSmpLen()];
        float[] t = new float[qvvrData.getSmpLen()];

        System.arraycopy(qvvrData.getSmpVa(), 0, va, 0, qvvrData.getSmpLen());
        System.arraycopy(qvvrData.getSmpVb(), 0, vb, 0, qvvrData.getSmpLen());
        System.arraycopy(qvvrData.getSmpVc(), 0, vc, 0, qvvrData.getSmpLen());

        // 生成时间数组
        for (int i = 0; i < qvvrData.getSmpLen(); i++) {
            t[i] = (0.02f / dataCause.getSmp()) * i;  // 按50Hz周期计算时间
        }

        dataCause.setVa(va);
        dataCause.setVb(vb);
        dataCause.setVc(vc);
        dataCause.setT(t);

        return dataCause;
    }

    /**
     * 输出特征详细信息
     * @param feature 特征结果
     */
    private void logFeatureDetails(DataFeature feature) {
        if (logger.isDebugEnabled()) {
            logger.debug("=== 电压暂降特征分析结果 ===");
            logger.debug("事件时段: TS={}, TE={}, 持续时间={}个采样点",
                    feature.getTS(), feature.getTE(), feature.getHoldTime());
            logger.debug("电压特征: 最小值={:.3f}, 最大值={:.3f}",
                    feature.getU3Min(), feature.getU3Max());
            logger.debug("统计特征: 标准差={:.3f}, 偏度={:.3f}, 峭度={:.3f}",
                    feature.getBiaozhun(), feature.getPian(), feature.getQiao());
            logger.debug("椭圆特征: bi1={:.3f}, bi2={:.3f}, 高斯性={:.3f}",
                    feature.getBi1(), feature.getBi2(), feature.getGao());
            logger.debug("相序特征: 负序={:.3f}, 零序={:.3f}, 不平衡度={:.3f}",
                    feature.getU2Avg(), feature.getU0Avg(), feature.getBphAvg());
            logger.debug("SVD特征: {:.6f}", feature.getSvd());
            logger.debug("稳态前异常: 不平衡={}, 谐波={}",
                    feature.getPreBphErr(), feature.getPreHarmErr());

            float[] harm2 = feature.getHarm2Avg();
            float[] harm4 = feature.getHarm4Avg();
            logger.debug("谐波特征: 2次=({:.3f},{:.3f},{:.3f}), 4次=({:.3f},{:.3f},{:.3f})",
                    harm2[0], harm2[1], harm2[2], harm4[0], harm4[1], harm4[2]);
        }
    }

    /**
     * 简化的分析接口 - 直接返回原因代码
     * @param va A相电压数据
     * @param vb B相电压数据
     * @param vc C相电压数据
     * @param smpRate 采样率
     * @return 暂降原因代码
     */
    public int analyzeSimple(float[] va, float[] vb, float[] vc, int smpRate) {
        QvvrDataStruct qvvrData = new QvvrDataStruct();
        qvvrData.setSmpVa(va);
        qvvrData.setSmpVb(vb);
        qvvrData.setSmpVc(vc);
        qvvrData.setSmpRate(smpRate);
        qvvrData.setSmpLen(va.length);

        int result = analyzeVoltageSag(qvvrData);
        if (result == 0) {
            return qvvrData.getCause();
        } else {
            return 0;  // 未知原因
        }
    }

    /**
     * 增强的分析函数 - 返回详细分析结果
     * @param qvvrData 输入的电压暂降数据结构
     * @return 包含详细信息的分析结果对象
     */
    public AnalysisResult analyzeVoltageSagWithDetails(QvvrDataStruct qvvrData) {
        long startTime = System.currentTimeMillis();

        // 构建输入信息描述
        String inputInfo = String.format("采样率=%d Hz, 数据长度=%d点",
                qvvrData.getSmpRate(), qvvrData.getSmpLen());

        try {
            logger.info("开始电压暂降分析，{}", inputInfo);

            // 参数校验
            if (!validateInput(qvvrData)) {
                qvvrData.setCause(0);
                qvvrData.setNoCal(1);
                return new AnalysisResult(1, "输入参数校验失败", inputInfo);
            }

            // 创建数据处理对象
            DataCause dataCause = createDataCause(qvvrData);
            DataFeature resultFeature = new DataFeature();

            // 特征值计算
            int ret = featureCalculator.calculateFeatures(dataCause, resultFeature);
            if (ret == 0) {
                // 阈值判断确定暂降原因
                int judgeStatus = ThresholdJudge.thresholdJudge(resultFeature);

                // 设置输出结果
                qvvrData.setCause(resultFeature.getCause());
                qvvrData.setNoCal(0);

                long processingTime = System.currentTimeMillis() - startTime;
                String causeDescription = ThresholdJudge.getCauseDescription(resultFeature.getCause());

                logger.info("分析完成，原因={} ({}), 处理时间={}ms, 判断状态={}",
                        resultFeature.getCause(), causeDescription, processingTime, judgeStatus);

                // 输出详细特征信息
                logFeatureDetails(resultFeature);

                // 返回成功结果
                return new AnalysisResult(resultFeature.getCause(), causeDescription,
                        judgeStatus, processingTime, resultFeature, inputInfo);
            } else {
                qvvrData.setCause(0);
                qvvrData.setNoCal(1);
                logger.error("特征计算失败");
                return new AnalysisResult(1, "特征计算失败", inputInfo);
            }

        } catch (Exception e) {
            logger.error("分析过程发生异常", e);
            qvvrData.setCause(0);
            qvvrData.setNoCal(1);
            return new AnalysisResult(1, "分析过程发生异常: " + e.getMessage(), inputInfo);
        }
    }

    /**
     * 简化的详细分析接口 - 直接返回分析结果对象
     * @param va A相电压数据
     * @param vb B相电压数据
     * @param vc C相电压数据
     * @param smpRate 采样率
     * @return 包含详细信息的分析结果对象
     */
    public AnalysisResult analyzeWithDetails(float[] va, float[] vb, float[] vc, int smpRate) {
        QvvrDataStruct qvvrData = new QvvrDataStruct();
        qvvrData.setSmpVa(va);
        qvvrData.setSmpVb(vb);
        qvvrData.setSmpVc(vc);
        qvvrData.setSmpRate(smpRate);
        qvvrData.setSmpLen(va.length);

        return analyzeVoltageSagWithDetails(qvvrData);
    }

    /**
     * 获取分析器版本信息
     * @return 版本字符串
     */
    public String getVersion() {
        return "Java Voltage Sag Analyzer v1.0.0 - Converted from C implementation";
    }
}