#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
园区能耗日报自动生成脚本
功能：采集能耗数据 → 计算碳排放 → 生成报表 → 发送通知
"""

import json
import os
from datetime import datetime, timedelta
from pathlib import Path

# ==================== 配置区域 ====================

# 数据源配置（根据实际数据源修改）
DATA_CONFIG = {
    "type": "csv",  # csv/api/database
    "csv_path": "/home/admin/.openclaw/data/energy_data.csv",
    "api_url": "http://ems-api.example.com/data",
    "db_connection": "sqlite:///energy.db"
}

# 园区配置
PARKS = [
    {"name": "园区 A", "code": "PK001"},
    {"name": "园区 B", "code": "PK002"},
    {"name": "园区 C", "code": "PK003"}
]

# 排放因子（中国电网 2022 年数据）
EMISSION_FACTORS = {
    "electricity": 0.5810,  # kg CO₂/kWh
    "natural_gas": 2.16,    # kg CO₂/m³
    "gasoline": 2.64,       # kg CO₂/L
    "diesel": 2.64          # kg CO₂/L
}

# 输出配置
OUTPUT_DIR = "/home/admin/.openclaw/workspace-agent-200/reports/"
REPORT_FORMAT = "markdown"  # markdown/html/pdf

# ==================== 数据采集 ====================

def collect_energy_data(date):
    """
    采集指定日期的能耗数据
    返回：dict {park_code: {electricity, water, gas, ...}}
    """
    data_type = DATA_CONFIG["type"]
    
    if data_type == "csv":
        return collect_from_csv(date)
    elif data_type == "api":
        return collect_from_api(date)
    elif data_type == "database":
        return collect_from_db(date)
    else:
        # 演示模式：生成模拟数据
        return generate_mock_data(date)


def collect_from_csv(date):
    """从 CSV 文件采集数据"""
    csv_path = DATA_CONFIG["csv_path"]
    if not os.path.exists(csv_path):
        print(f"警告：CSV 文件不存在 {csv_path}")
        return generate_mock_data(date)
    
    # TODO: 实现 CSV 读取逻辑
    return generate_mock_data(date)


def collect_from_api(date):
    """从 API 采集数据"""
    import requests
    # TODO: 实现 API 调用逻辑
    return generate_mock_data(date)


def collect_from_db(date):
    """从数据库采集数据"""
    # TODO: 实现数据库查询逻辑
    return generate_mock_data(date)


def generate_mock_data(date):
    """生成模拟数据（演示用）"""
    import random
    
    data = {}
    for park in PARKS:
        data[park["code"]] = {
            "name": park["name"],
            "electricity": random.randint(5000, 20000),  # kWh
            "water": random.randint(100, 500),           # m³
            "gas": random.randint(200, 1000),            # m³
            "pv_generation": random.randint(1000, 5000), # kWh
            "storage_charge": random.randint(500, 2000), # kWh
            "storage_discharge": random.randint(500, 2000) # kWh
        }
    return data


# ==================== 碳排放计算 ====================

def calculate_carbon_emissions(data):
    """
    计算碳排放量
    返回：dict {park_code: {emissions, breakdown}}
    """
    results = {}
    
    for park_code, park_data in data.items():
        electricity_emission = park_data.get("electricity", 0) * EMISSION_FACTORS["electricity"]
        gas_emission = park_data.get("gas", 0) * EMISSION_FACTORS["natural_gas"]
        
        total_emission = electricity_emission + gas_emission
        
        results[park_code] = {
            "total": total_emission,
            "breakdown": {
                "electricity": electricity_emission,
                "natural_gas": gas_emission
            }
        }
    
    return results


# ==================== 报表生成 ====================

def generate_report(date, energy_data, carbon_data):
    """生成能耗日报"""
    
    template_path = os.path.join(OUTPUT_DIR, "能耗日报模板.md")
    with open(template_path, "r", encoding="utf-8") as f:
        template = f.read()
    
    # 计算汇总数据
    total_electricity = sum(d.get("electricity", 0) for d in energy_data.values())
    total_water = sum(d.get("water", 0) for d in energy_data.values())
    total_gas = sum(d.get("gas", 0) for d in energy_data.values())
    total_carbon = sum(c["total"] for c in carbon_data.values())
    total_pv = sum(d.get("pv_generation", 0) for d in energy_data.values())
    
    # 替换模板变量
    report = template.replace("{{date}}", date.strftime("%Y-%m-%d"))
    report = report.replace("{{timestamp}}", datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    report = report.replace("{{start_time}}", date.strftime("%Y-%m-%d 00:00:00"))
    report = report.replace("{{end_time}}", date.strftime("%Y-%m-%d 23:59:59"))
    
    # 填充分园区数据
    park_rows = ""
    for park_code, park_data in energy_data.items():
        carbon = carbon_data.get(park_code, {}).get("total", 0)
        ratio = (park_data.get("electricity", 0) / total_electricity * 100) if total_electricity > 0 else 0
        park_rows += f"| {park_data.get('name', park_code)} | {park_data.get('electricity', 0)} | {park_data.get('water', 0)} | {park_data.get('gas', 0)} | {carbon:.2f} | {ratio:.1f}% |\n"
    
    report = report.replace("| 园区 A | -- | -- | -- | -- | -- |\n| 园区 B | -- | -- | -- | -- | -- |\n| 园区 C | -- | -- | -- | -- | -- |\n", park_rows)
    
    # 填充汇总数据
    report = report.replace("| 总用电量 | -- |", f"| 总用电量 | {total_electricity} |")
    report = report.replace("| 总用水的 | -- |", f"| 总用水的 | {total_water} |")
    report = report.replace("| 总用气量 | -- |", f"| 总用气量 | {total_gas} |")
    report = report.replace("| 碳排放量 | -- |", f"| 碳排放量 | {total_carbon:.2f} |")
    
    # 填充光伏储能数据
    report = report.replace("| 光伏今日发电量 | -- |", f"| 光伏今日发电量 | {total_pv} |")
    
    # 填充碳排放核算
    electricity_emission = total_electricity * EMISSION_FACTORS["electricity"]
    gas_emission = total_gas * EMISSION_FACTORS["natural_gas"]
    carbon_table = f"""| 外购电力 | {total_electricity} kWh | 0.5810 kg/kWh | {electricity_emission:.2f} | {electricity_emission/total_carbon*100 if total_carbon>0 else 0:.1f}% |
| 天然气 | {total_gas} m³ | 2.16 kg/m³ | {gas_emission:.2f} | {gas_emission/total_carbon*100 if total_carbon>0 else 0:.1f}% |
| **合计** | -- | -- | **{total_carbon:.2f}** | **100%** |"""
    report = report.replace("| 外购电力 | -- kWh | 0.5810 kg/kWh | -- | -- |\n| 天然气 | -- m³ | 2.16 kg/m³ | -- | -- |\n| 汽油/柴油 | -- L | 2.64 kg/L | -- | -- |\n| **合计** | -- | -- | **--** | **100%** |", carbon_table)
    
    # 填充数据说明
    report = report.replace("{{data_source}}", "模拟数据（请配置真实数据源）")
    report = report.replace("{{sampling_rate}}", "15 分钟")
    report = report.replace("{{completeness}}", "100")
    report = report.replace("{{notes}}", "首次运行，使用模拟数据演示")
    report = report.replace("{{next_update}}", (date + timedelta(days=1)).strftime("%Y-%m-%d 08:00"))
    
    # 保存报表
    output_file = os.path.join(OUTPUT_DIR, f"能耗日报_{date.strftime('%Y%m%d')}.md")
    with open(output_file, "w", encoding="utf-8") as f:
        f.write(report)
    
    return output_file


# ==================== 通知发送 ====================

def send_notification(report_path, recipients):
    """发送报表通知"""
    # TODO: 实现邮件/钉钉/企业微信通知
    print(f"报表已生成：{report_path}")
    print(f"通知收件人：{recipients}")


# ==================== 主程序 ====================

def main():
    """主程序入口"""
    
    # 获取日期（默认昨天）
    report_date = datetime.now() - timedelta(days=1)
    
    print(f"=== 能耗日报自动生成 ===")
    print(f"报表日期：{report_date.strftime('%Y-%m-%d')}")
    print(f"开始时间：{datetime.now().strftime('%H:%M:%S')}")
    
    # 1. 采集数据
    print("\n[1/4] 采集能耗数据...")
    energy_data = collect_energy_data(report_date)
    print(f"  已采集 {len(energy_data)} 个园区数据")
    
    # 2. 计算碳排放
    print("\n[2/4] 计算碳排放...")
    carbon_data = calculate_carbon_emissions(energy_data)
    total_carbon = sum(c["total"] for c in carbon_data.values())
    print(f"  总碳排放：{total_carbon:.2f} kg CO₂e")
    
    # 3. 生成报表
    print("\n[3/4] 生成报表...")
    report_path = generate_report(report_date, energy_data, carbon_data)
    print(f"  报表路径：{report_path}")
    
    # 4. 发送通知
    print("\n[4/4] 发送通知...")
    recipients = ["admin@example.com"]  # 配置收件人
    send_notification(report_path, recipients)
    
    print("\n=== 生成完成 ===")
    return report_path


if __name__ == "__main__":
    main()
