#!/usr/bin/env python3
import argparse
import requests
import json
import os
import subprocess

API_BASE_URL = "http://47.96.16.84:5006"

# 正确的路径计算
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
SKILL_DIR = os.path.dirname(SCRIPT_DIR)
# 计算report-generator的路径
REPORT_GENERATOR_DIR = os.path.join(os.path.dirname(SKILL_DIR), "report-generator")

def generate_report(weather_data, station_name, forecast_days):
    """
    生成气象预测报告
    """
    # 准备报告数据
    report_data = []
    
    # 提取气象数据
    if weather_data and weather_data.get('success'):
        weather_info = weather_data.get('weather_data', {})
        hourly_data = weather_info.get('hourly', {})
        minutely_data = weather_info.get('minutely_15', {})
        
        # 使用分钟级数据（15分钟间隔）
        if minutely_data:
            times = minutely_data.get('time', [])
            temperatures = minutely_data.get('temperature_2m', [])
            humidity = minutely_data.get('relative_humidity_2m', [])
            radiation = minutely_data.get('shortwave_radiation', [])
            
            for i, time_str in enumerate(times):
                # 格式化时间
                formatted_time = time_str.split('T')[1] if 'T' in time_str else time_str
                report_data.append({
                    "time": formatted_time,
                    "temperature": temperatures[i] if i < len(temperatures) else None,
                    "humidity": humidity[i] if i < len(humidity) else None,
                    "radiation": radiation[i] if i < len(radiation) else None
                })
        # 如果没有分钟级数据，使用小时级数据
        elif hourly_data:
            times = hourly_data.get('time', [])
            cloud_cover = hourly_data.get('cloud_cover', [])
            
            for i, time_str in enumerate(times):
                formatted_time = time_str.split('T')[1] if 'T' in time_str else time_str
                report_data.append({
                    "time": formatted_time,
                    "cloud_cover": cloud_cover[i] if i < len(cloud_cover) else None
                })
    
    # 调用step1_select.py选择模板
    step1_script = os.path.join(REPORT_GENERATOR_DIR, "scripts", "step1_select.py")
    if not os.path.exists(step1_script):
        raise Exception(f"Step1 script not found at {step1_script}")
    
    user_query = f"{station_name}站点{forecast_days}天气象预测数据"
    step1_cmd = ["python", step1_script, "--query", user_query, "--data", json.dumps(report_data, ensure_ascii=False)]
    step1_result = subprocess.run(step1_cmd, capture_output=True, text=True, timeout=60)
    
    if step1_result.returncode != 0:
        raise Exception(f"Step 1 failed: {step1_result.stderr}")
    
    lines = step1_result.stdout.strip().split('\n')
    step1_output = None
    for line in reversed(lines):
        try:
            step1_output = json.loads(line)
            break
        except:
            continue
    
    if step1_output is None or step1_output.get("status") != "success":
        raise Exception(f"Template selection failed")
    
    template_name = step1_output.get("template_name", "lineChart")
    
    # 调用step2_render.py生成报告
    step2_script = os.path.join(REPORT_GENERATOR_DIR, "scripts", "step2_render.py")
    if not os.path.exists(step2_script):
        raise Exception(f"Step2 script not found at {step2_script}")
    
    step2_cmd = ["python", step2_script, "--query", user_query, "--template", template_name, "--data", json.dumps(report_data, ensure_ascii=False)]
    step2_result = subprocess.run(step2_cmd, capture_output=True, text=True, timeout=60)
    
    if step2_result.returncode != 0:
        raise Exception(f"Step 2 failed: {step2_result.stderr}")
    
    lines = step2_result.stdout.strip().split('\n')
    step2_output = None
    for line in reversed(lines):
        try:
            step2_output = json.loads(line)
            break
        except:
            continue
    
    if step2_output is None or step2_output.get("status") != "success":
        raise Exception(f"Report generation failed")
    
    report_address = step2_output.get('address', '')
    summary = step2_output.get('summary', '')
    
    print("\nGENERATING REPORT")
    print("=" * 60)
    print("PROGRESSION: ⏳ 正在分析数据，选择合适的可视化模板...")
    print(f"Selected template: {template_name}")
    print("PROGRESSION: ⏳ 正在将数据渲染为图表报告...")
    print("")
    print("✓ Report generated successfully!")
    
    print(f"Summary: {summary}")
    print("")
    print(f"@@@@@{report_address}@@@@@")
    print("")
    print("#####%查看详细数据%￥点击上方链接查看完整的数据分析报告￥ %继续深入分析%￥基于当前数据进行更深度的挖掘￥ %导出报告%￥将当前报告导出为PDF或图片格式￥#####")
    
    return report_address


def get_weather_forecast(station_name, forecast_days=1):
    """
    获取气象预测数据
    
    参数:
    station_name: 站点名称
    forecast_days: 预测天数，1或2
    
    返回:
    气象预测数据
    """

    url = f"{API_BASE_URL}/api/weather/forecast"
    
    data = {
        "station_name": station_name,
        "forecast_days": forecast_days
    }
    
    headers = {
        "Content-Type": "application/json"
    }
    
    try:
        response = requests.post(url, json=data, headers=headers, timeout=30)
        response.raise_for_status()
        result = response.json()
        print("气象预测接口调用成功！")
        print("返回内容:")
        print(json.dumps(result, indent=2, ensure_ascii=False))
        
        # 生成报告
        try:
            generate_report(result, station_name, forecast_days)
        except Exception as e:
            print(f"报告生成失败: {e}")
        
        return result
    except Exception as e:
        print(f"气象预测接口调用失败: {e}")
        return None

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='获取气象预测数据')
    parser.add_argument('--station_name', type=str, required=True, help='站点名称')
    parser.add_argument('--forecast_days', type=int, default=1, choices=[1, 2], help='预测天数，1或2')
    args = parser.parse_args()
    
    get_weather_forecast(
        station_name=args.station_name,
        forecast_days=args.forecast_days
    )