#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
台灣天氣查詢工具
使用中央氣象署開放資料 API

用法：
    python weather.py 台北           # 36 小時預報
    python weather.py 台北 --week    # 一週預報
    python weather.py --all          # 全台天氣概況
    python weather.py --now          # 即時觀測（全台測站）
    python weather.py --earthquake   # 最近地震報告
    python weather.py --alert        # 當前警特報
"""

import sys
import os
import argparse
import requests
from datetime import datetime

# Windows 編碼處理
sys.stdout.reconfigure(encoding='utf-8')

# 地名對照表（常用簡稱 → 正式名稱）
LOCATION_ALIASES = {
    # 直轄市
    '台北': '臺北市', '臺北': '臺北市', '台北市': '臺北市',
    '新北': '新北市',
    '桃園': '桃園市',
    '台中': '臺中市', '臺中': '臺中市', '台中市': '臺中市',
    '台南': '臺南市', '臺南': '臺南市', '台南市': '臺南市',
    '高雄': '高雄市',
    # 縣市
    '基隆': '基隆市',
    '新竹': '新竹市',  # 預設為市
    '新竹市': '新竹市',
    '新竹縣': '新竹縣',
    '苗栗': '苗栗縣',
    '彰化': '彰化縣',
    '南投': '南投縣',
    '雲林': '雲林縣',
    '嘉義': '嘉義市',  # 預設為市
    '嘉義市': '嘉義市',
    '嘉義縣': '嘉義縣',
    '屏東': '屏東縣',
    '宜蘭': '宜蘭縣',
    '花蓮': '花蓮縣',
    '台東': '臺東縣', '臺東': '臺東縣',
    # 離島
    '澎湖': '澎湖縣',
    '金門': '金門縣',
    '馬祖': '連江縣', '連江': '連江縣',
}


def get_api_key():
    """取得 API Key（支援系統環境變數和 Windows 使用者環境變數）"""
    # 1. 先嘗試從系統環境變數取得
    api_key = os.environ.get('CWA_API_KEY')

    # 2. 如果沒有，嘗試從 Windows 使用者環境變數取得
    if not api_key and sys.platform == 'win32':
        import subprocess
        try:
            result = subprocess.run(
                ['powershell', '-Command',
                 "[Environment]::GetEnvironmentVariable('CWA_API_KEY', 'User')"],
                capture_output=True, text=True, timeout=5
            )
            api_key = result.stdout.strip()
        except Exception:
            pass

    if not api_key:
        print('錯誤：未設定環境變數 CWA_API_KEY')
        print('請執行：')
        print('  PowerShell: [Environment]::SetEnvironmentVariable("CWA_API_KEY", "你的授權碼", "User")')
        sys.exit(1)
    return api_key


def normalize_location(name):
    """正規化地名"""
    name = name.strip()
    return LOCATION_ALIASES.get(name, name)


def fetch_weather(location=None):
    """
    從中央氣象署 API 取得天氣資料

    Args:
        location: 縣市名稱（None 表示取得全部）

    Returns:
        dict: API 回傳的 JSON 資料
    """
    api_key = get_api_key()
    url = 'https://opendata.cwa.gov.tw/api/v1/rest/datastore/F-C0032-001'

    params = {'Authorization': api_key}
    if location:
        params['locationName'] = normalize_location(location)

    try:
        response = requests.get(url, params=params, timeout=10)
        response.raise_for_status()
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f'API 請求失敗：{e}')
        sys.exit(1)


def fetch_weekly_weather():
    """
    從中央氣象署 API 取得一週天氣預報

    Returns:
        dict: API 回傳的 JSON 資料
    """
    api_key = get_api_key()
    url = 'https://opendata.cwa.gov.tw/api/v1/rest/datastore/F-D0047-091'

    params = {'Authorization': api_key}

    try:
        response = requests.get(url, params=params, timeout=10)
        response.raise_for_status()
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f'API 請求失敗：{e}')
        sys.exit(1)


def parse_weekly_data(data, location):
    """
    解析一週天氣預報資料

    Args:
        data: API 回傳的 JSON 資料
        location: 要查詢的縣市名稱

    Returns:
        list: 一週預報資料列表
    """
    results = []
    normalized = normalize_location(location)

    if data.get('success') != 'true':
        print(f'API 回傳錯誤：{data}')
        return results

    # 搜尋指定縣市
    for loc_data in data['records']['Locations']:
        for loc in loc_data['Location']:
            if loc['LocationName'] == normalized:
                elements = {e['ElementName']: e['Time'] for e in loc['WeatherElement']}

                wx = elements.get('天氣現象', [])
                pop = elements.get('12小時降雨機率', [])
                max_t = elements.get('最高溫度', [])
                min_t = elements.get('最低溫度', [])
                humidity = elements.get('平均相對濕度', [])
                uv = elements.get('紫外線指數', [])
                wind_speed = elements.get('風速', [])
                wind_dir = elements.get('風向', [])
                dew_point = elements.get('平均露點溫度', [])

                for i in range(min(14, len(wx))):  # 7 天 x 2 時段
                    start_time = wx[i]['StartTime']
                    end_time = wx[i]['EndTime']

                    # 判斷白天/夜晚
                    hour = int(start_time[11:13])
                    period = '白天' if 6 <= hour < 18 else '夜晚'

                    weather = wx[i]['ElementValue'][0].get('Weather', '-')
                    t_max = max_t[i]['ElementValue'][0].get('MaxTemperature', '-') if i < len(max_t) else '-'
                    t_min = min_t[i]['ElementValue'][0].get('MinTemperature', '-') if i < len(min_t) else '-'
                    rain = pop[i]['ElementValue'][0].get('ProbabilityOfPrecipitation', '-') if i < len(pop) else '-'

                    # 新增欄位
                    rh = humidity[i]['ElementValue'][0].get('RelativeHumidity', '-') if i < len(humidity) else '-'

                    # 紫外線只有白天有資料
                    uv_index = '-'
                    uv_level = '-'
                    if i < len(uv) and uv[i]['ElementValue']:
                        uv_index = uv[i]['ElementValue'][0].get('UVIndex', '-')
                        uv_level = uv[i]['ElementValue'][0].get('UVExposureLevel', '-')

                    ws = '-'
                    beaufort = '-'
                    if i < len(wind_speed) and wind_speed[i]['ElementValue']:
                        ws = wind_speed[i]['ElementValue'][0].get('WindSpeed', '-')
                        beaufort = wind_speed[i]['ElementValue'][0].get('BeaufortScale', '-')

                    wd = wind_dir[i]['ElementValue'][0].get('WindDirection', '-') if i < len(wind_dir) else '-'
                    dp = dew_point[i]['ElementValue'][0].get('DewPoint', '-') if i < len(dew_point) else '-'

                    results.append({
                        'date': start_time[:10],
                        'period': period,
                        'weather': weather,
                        'min_temp': t_min,
                        'max_temp': t_max,
                        'rain_prob': rain,
                        'humidity': rh,
                        'uv_index': uv_index,
                        'uv_level': uv_level,
                        'wind_speed': ws,
                        'wind_beaufort': beaufort,
                        'wind_dir': wd,
                        'dew_point': dp,
                    })

                return results

    return results


def get_uv_warning(uv_index):
    """根據紫外線指數回傳警示等級"""
    if uv_index == '-' or uv_index == '':
        return ''
    try:
        uv = int(uv_index)
        if uv >= 11:
            return ' (危險)'
        elif uv >= 8:
            return ' (過量)'
        elif uv >= 6:
            return ' (高)'
        elif uv >= 3:
            return ' (中)'
        else:
            return ' (低)'
    except ValueError:
        return ''


def print_weekly_weather(location, weekly_data):
    """輸出一週天氣預報"""
    print(f"\n{'='*90}")
    print(f"  {location} 一週天氣預報")
    print(f"{'='*90}\n")

    # 基本資訊表格
    print("【基本天氣】")
    print(f"{'日期':<12} {'時段':<4} {'天氣':<14} {'溫度':<10} {'降雨':<6} {'濕度':<6}")
    print("-" * 70)

    for w in weekly_data:
        rain_str = f"{w['rain_prob']:>3}%" if w['rain_prob'] != '-' else "  - "
        humidity_str = f"{w['humidity']:>3}%" if w['humidity'] != '-' else "  - "
        print(f"{w['date']}  {w['period']:<4} {w['weather']:<14} {w['min_temp']:>2}-{w['max_temp']}°C  {rain_str}  {humidity_str}")

    # 詳細資訊表格（紫外線、風速風向、露點）
    print(f"\n{'='*90}")
    print("【詳細資訊】")
    print(f"{'日期':<12} {'時段':<4} {'紫外線':<12} {'風向':<6} {'風速':<12} {'露點':<6}")
    print("-" * 70)

    for w in weekly_data:
        # 紫外線
        if w['uv_index'] != '-' and w['uv_index'] != '':
            uv_str = f"UV {w['uv_index']}{get_uv_warning(w['uv_index'])}"
        else:
            uv_str = "-"

        # 風速（蒲福氏風級）
        if w['wind_speed'] != '-':
            wind_str = f"{w['wind_speed']}m/s ({w['wind_beaufort']}級)"
        else:
            wind_str = "-"

        # 風向
        wind_dir_str = w['wind_dir'] if w['wind_dir'] != '-' else "-"

        # 露點
        dew_str = f"{w['dew_point']}°C" if w['dew_point'] != '-' else "-"

        print(f"{w['date']}  {w['period']:<4} {uv_str:<12} {wind_dir_str:<6} {wind_str:<12} {dew_str:<6}")

    # 圖例說明
    print(f"\n{'='*90}")
    print("【圖例說明】")
    print("  紫外線指數：0-2 低 | 3-5 中 | 6-7 高 | 8-10 過量 | 11+ 危險")
    print("  蒲福氏風級：0 無風 | 1-3 輕風 | 4-5 和風 | 6-7 強風 | 8+ 烈風")
    print("  露點溫度：接近氣溫時表示濕度高、體感悶熱")
    print()


def parse_weather_data(data):
    """
    解析天氣資料

    Returns:
        list: 各縣市天氣資料列表
    """
    results = []

    if data.get('success') != 'true':
        print(f'API 回傳錯誤：{data}')
        return results

    for location in data['records']['location']:
        loc_name = location['locationName']
        elements = {e['elementName']: e['time'] for e in location['weatherElement']}

        # 取得最近一筆預報
        current = {
            'location': loc_name,
            'start_time': elements['Wx'][0]['startTime'],
            'end_time': elements['Wx'][0]['endTime'],
            'weather': elements['Wx'][0]['parameter']['parameterName'],
            'rain_prob': elements['PoP'][0]['parameter']['parameterName'],
            'min_temp': elements['MinT'][0]['parameter']['parameterName'],
            'max_temp': elements['MaxT'][0]['parameter']['parameterName'],
            'comfort': elements['CI'][0]['parameter']['parameterName'],
        }

        # 取得下一筆預報（如果有）
        if len(elements['Wx']) > 1:
            current['next'] = {
                'start_time': elements['Wx'][1]['startTime'],
                'end_time': elements['Wx'][1]['endTime'],
                'weather': elements['Wx'][1]['parameter']['parameterName'],
                'rain_prob': elements['PoP'][1]['parameter']['parameterName'],
                'min_temp': elements['MinT'][1]['parameter']['parameterName'],
                'max_temp': elements['MaxT'][1]['parameter']['parameterName'],
                'comfort': elements['CI'][1]['parameter']['parameterName'],
            }

        results.append(current)

    return results


def format_time(time_str):
    """格式化時間（只取時間部分）"""
    # 2026-01-08 06:00:00 → 06:00
    return time_str.split(' ')[1][:5]


def print_weather(weather_list, show_next=True):
    """輸出天氣資訊"""
    for w in weather_list:
        print(f"\n{'='*40}")
        print(f"  {w['location']}")
        print(f"{'='*40}")

        time_range = f"{format_time(w['start_time'])} ~ {format_time(w['end_time'])}"
        print(f"\n  【現在 ~ {time_range}】")
        print(f"  天氣：{w['weather']}")
        print(f"  溫度：{w['min_temp']} ~ {w['max_temp']}°C")
        print(f"  降雨機率：{w['rain_prob']}%")
        print(f"  體感：{w['comfort']}")

        if show_next and 'next' in w:
            n = w['next']
            time_range = f"{format_time(n['start_time'])} ~ {format_time(n['end_time'])}"
            print(f"\n  【稍後 ~ {time_range}】")
            print(f"  天氣：{n['weather']}")
            print(f"  溫度：{n['min_temp']} ~ {n['max_temp']}°C")
            print(f"  降雨機率：{n['rain_prob']}%")
            print(f"  體感：{n['comfort']}")

    print()


def print_summary(weather_list):
    """輸出全台天氣摘要"""
    print("\n" + "="*50)
    print("  全台天氣概況")
    print("="*50 + "\n")

    print(f"{'縣市':<6} {'天氣':<10} {'溫度':<10} {'降雨':>5}")
    print("-"*40)

    for w in weather_list:
        temp = f"{w['min_temp']}-{w['max_temp']}°C"
        print(f"{w['location']:<6} {w['weather']:<10} {temp:<10} {w['rain_prob']:>4}%")

    print()


# ============================================================
# 即時觀測功能
# ============================================================

def fetch_observation():
    """
    從中央氣象署 API 取得即時觀測資料（全台自動氣象站）

    API: O-A0001-001 - 自動氣象站-氣象觀測資料
    """
    api_key = get_api_key()
    url = 'https://opendata.cwa.gov.tw/api/v1/rest/datastore/O-A0001-001'
    params = {'Authorization': api_key}

    try:
        response = requests.get(url, params=params, timeout=10)
        response.raise_for_status()
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f'API 請求失敗：{e}')
        sys.exit(1)


def parse_observation(data, location=None):
    """
    解析即時觀測資料

    Args:
        data: API 回傳的 JSON
        location: 指定縣市（None 表示全部）

    Returns:
        list: 觀測站資料列表
    """
    results = []

    if data.get('success') != 'true':
        print(f'API 回傳錯誤：{data}')
        return results

    for station in data['records']['Station']:
        # 篩選指定縣市
        if location:
            normalized = normalize_location(location)
            if station.get('GeoInfo', {}).get('CountyName', '') != normalized:
                continue

        obs = station.get('ObsTime', {}).get('DateTime', '-')
        weather_elem = station.get('WeatherElement', {})
        geo = station.get('GeoInfo', {})

        results.append({
            'station_name': station.get('StationName', '-'),
            'station_id': station.get('StationId', '-'),
            'county': geo.get('CountyName', '-'),
            'town': geo.get('TownName', '-'),
            'altitude': geo.get('StationAltitude', '-'),
            'obs_time': obs,
            'weather': weather_elem.get('Weather', '-'),
            'temperature': weather_elem.get('AirTemperature', '-'),
            'humidity': weather_elem.get('RelativeHumidity', '-'),
            'wind_speed': weather_elem.get('WindSpeed', '-'),
            'wind_dir': weather_elem.get('WindDirection', '-'),
            'pressure': weather_elem.get('AirPressure', '-'),
            'rain_1h': weather_elem.get('Now', {}).get('Precipitation', '-'),
        })

    # 按海拔高度排序（高到低）
    results.sort(key=lambda x: float(x['altitude']) if x['altitude'] != '-' else 0, reverse=True)

    return results


def print_observation(obs_list, location=None):
    """輸出即時觀測資料"""
    title = f"{location} " if location else "全台 "
    print(f"\n{'='*90}")
    print(f"  {title}即時觀測資料")
    print(f"{'='*90}\n")

    if not obs_list:
        print("  沒有觀測資料")
        return

    # 取觀測時間（假設所有站大致相同）
    if obs_list:
        print(f"  觀測時間：{obs_list[0]['obs_time']}")
        print()

    print(f"{'測站':<10} {'海拔':>7} {'溫度':>7} {'濕度':>6} {'風速':>8} {'降雨':>8}")
    print("-" * 70)

    for obs in obs_list:
        alt = f"{float(obs['altitude']):,.0f}m" if obs['altitude'] != '-' else '-'
        temp = f"{obs['temperature']}°C" if obs['temperature'] != '-' else '-'
        hum = f"{obs['humidity']}%" if obs['humidity'] != '-' else '-'
        wind = f"{obs['wind_speed']}m/s" if obs['wind_speed'] != '-' else '-'
        rain = f"{obs['rain_1h']}mm" if obs['rain_1h'] != '-' else '-'

        print(f"{obs['station_name']:<10} {alt:>7} {temp:>7} {hum:>6} {wind:>8} {rain:>8}")

    print(f"\n  共 {len(obs_list)} 個觀測站")
    print()


# ============================================================
# 地震報告功能
# ============================================================

def fetch_earthquake(limit=5):
    """
    從中央氣象署 API 取得最近地震報告

    API: E-A0016-002 - 有感地震報告
    """
    api_key = get_api_key()
    url = 'https://opendata.cwa.gov.tw/api/v1/rest/datastore/E-A0016-002'
    params = {
        'Authorization': api_key,
        'limit': limit
    }

    try:
        response = requests.get(url, params=params, timeout=10)
        response.raise_for_status()
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f'API 請求失敗：{e}')
        sys.exit(1)


def parse_earthquake(data):
    """解析地震報告資料"""
    results = []

    if data.get('success') != 'true':
        print(f'API 回傳錯誤：{data}')
        return results

    for eq in data.get('records', {}).get('Earthquake', []):
        info = eq.get('EarthquakeInfo', {})
        epicenter = info.get('Epicenter', {})
        magnitude = info.get('EarthquakeMagnitude', {})

        results.append({
            'no': eq.get('EarthquakeNo', '-'),
            'time': info.get('OriginTime', '-'),
            'location': epicenter.get('Location', '-'),
            'lat': epicenter.get('EpicenterLatitude', '-'),
            'lon': epicenter.get('EpicenterLongitude', '-'),
            'depth': info.get('FocalDepth', '-'),
            'magnitude': magnitude.get('MagnitudeValue', '-'),
            'magnitude_type': magnitude.get('MagnitudeType', '-'),
            'report_content': eq.get('ReportContent', '-'),
        })

    return results


def print_earthquake(eq_list):
    """輸出地震報告"""
    print(f"\n{'='*90}")
    print("  最近地震報告")
    print(f"{'='*90}\n")

    if not eq_list:
        print("  沒有地震報告")
        return

    for i, eq in enumerate(eq_list, 1):
        print(f"  【第 {i} 筆】地震編號：{eq['no']}")
        print(f"  發生時間：{eq['time']}")
        print(f"  震央位置：{eq['location']}")
        print(f"  座標：{eq['lat']}°N, {eq['lon']}°E")
        print(f"  深度：{eq['depth']} km")
        print(f"  規模：{eq['magnitude']} {eq['magnitude_type']}")
        print(f"  摘要：{eq['report_content']}")
        print("-" * 70)

    print()


# ============================================================
# 警特報功能
# ============================================================

def fetch_alert():
    """
    從中央氣象署 API 取得當前警特報

    API: W-C0034-001 - 天氣警特報
    """
    api_key = get_api_key()
    url = 'https://opendata.cwa.gov.tw/api/v1/rest/datastore/W-C0034-001'
    params = {'Authorization': api_key}

    try:
        response = requests.get(url, params=params, timeout=10)
        response.raise_for_status()
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f'API 請求失敗：{e}')
        sys.exit(1)


def parse_alert(data):
    """解析警特報資料"""
    results = []

    if data.get('success') != 'true':
        print(f'API 回傳錯誤：{data}')
        return results

    records = data.get('records', {}).get('record', [])
    for record in records:
        hazard = record.get('hazardConditions', {}).get('hazards', {}).get('hazard', {})
        valid_time = record.get('validTime', {})

        # 處理影響區域
        affected = record.get('affectedAreas', {}).get('location', [])
        if isinstance(affected, list):
            areas = ', '.join([a.get('locationName', '') for a in affected])
        else:
            areas = affected.get('locationName', '-')

        results.append({
            'headline': record.get('datasetInfo', {}).get('datasetDescription', '-'),
            'hazard_type': hazard.get('info', {}).get('phenomena', '-') if isinstance(hazard, dict) else '-',
            'significance': hazard.get('info', {}).get('significance', '-') if isinstance(hazard, dict) else '-',
            'start_time': valid_time.get('startTime', '-'),
            'end_time': valid_time.get('endTime', '-'),
            'affected_areas': areas,
            'content': record.get('contents', {}).get('content', {}).get('contentText', '-'),
        })

    return results


def print_alert(alert_list):
    """輸出警特報"""
    print(f"\n{'='*90}")
    print("  當前氣象警特報")
    print(f"{'='*90}\n")

    if not alert_list:
        print("  目前沒有發布警特報")
        print()
        return

    for i, alert in enumerate(alert_list, 1):
        print(f"  【第 {i} 筆】{alert['headline']}")
        print(f"  類型：{alert['hazard_type']} - {alert['significance']}")
        print(f"  生效時間：{alert['start_time']} ~ {alert['end_time']}")
        print(f"  影響區域：{alert['affected_areas']}")
        if alert['content'] != '-':
            # 內容可能很長，顯示前 200 字
            content = alert['content'][:200] + '...' if len(alert['content']) > 200 else alert['content']
            print(f"  內容：{content}")
        print("-" * 70)

    print()


# ============================================================
# 空氣品質 AQI 功能
# ============================================================

# 環境部開放資料 API Key（公開金鑰）
MOENV_API_KEY = '4c89a32a-a214-461b-bf29-30ff32a61a8a'

# AQI 狀態對照表
AQI_STATUS = {
    (0, 50): ('良好', '🟢', '空氣品質良好，適合戶外活動'),
    (51, 100): ('普通', '🟡', '空氣品質普通，敏感族群應注意'),
    (101, 150): ('對敏感族群不健康', '🟠', '敏感族群應減少戶外活動'),
    (151, 200): ('不健康', '🔴', '所有人應減少戶外活動'),
    (201, 300): ('非常不健康', '🟣', '所有人應避免戶外活動'),
    (301, 500): ('危害', '🟤', '所有人應留在室內'),
}


def get_aqi_info(aqi_value):
    """根據 AQI 數值取得狀態資訊"""
    try:
        aqi = int(aqi_value)
        for (low, high), (status, emoji, suggestion) in AQI_STATUS.items():
            if low <= aqi <= high:
                return status, emoji, suggestion
        return '未知', '⚪', ''
    except (ValueError, TypeError):
        return '無資料', '⚪', ''


def fetch_aqi(location=None):
    """
    從環境部 API 取得空氣品質資料

    API: aqx_p_432 - 空氣品質指標(AQI)
    資料來源：https://data.moenv.gov.tw
    """
    url = 'https://data.moenv.gov.tw/api/v2/aqx_p_432'
    params = {
        'api_key': MOENV_API_KEY,
        'limit': 1000,
        'format': 'JSON'
    }

    try:
        response = requests.get(url, params=params, timeout=10)
        response.raise_for_status()
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f'API 請求失敗：{e}')
        sys.exit(1)


def parse_aqi(data, location=None):
    """
    解析空氣品質資料

    Args:
        data: API 回傳的 JSON
        location: 指定縣市（None 表示全部）

    Returns:
        list: 測站空氣品質列表
    """
    results = []

    for record in data.get('records', []):
        county = record.get('county', '')

        # 篩選指定縣市
        if location:
            normalized = normalize_location(location)
            # 環境部資料的縣市名稱格式與氣象署略有不同
            if normalized not in county and county not in normalized:
                continue

        aqi_val = record.get('aqi', '')
        status, emoji, suggestion = get_aqi_info(aqi_val)

        results.append({
            'sitename': record.get('sitename', '-'),
            'county': county,
            'aqi': aqi_val,
            'status': record.get('status', status),
            'emoji': emoji,
            'suggestion': suggestion,
            'pm25': record.get('pm2.5', '-'),
            'pm10': record.get('pm10', '-'),
            'o3': record.get('o3', '-'),
            'co': record.get('co', '-'),
            'so2': record.get('so2', '-'),
            'no2': record.get('no2', '-'),
            'pollutant': record.get('pollutant', '-'),
            'publishtime': record.get('publishtime', '-'),
        })

    # 按 AQI 數值排序（高到低，顯示最差的在前面）
    def get_aqi_sort_key(x):
        try:
            return int(x['aqi'])
        except (ValueError, TypeError):
            return 0
    results.sort(key=get_aqi_sort_key, reverse=True)

    return results


def print_aqi(aqi_list, location=None):
    """輸出空氣品質資料"""
    title = f"{location} " if location else "全台 "
    print(f"\n{'='*90}")
    print(f"  {title}空氣品質指標 (AQI)")
    print(f"{'='*90}\n")

    if not aqi_list:
        print("  沒有空氣品質資料")
        return

    # 取發布時間
    if aqi_list:
        print(f"  資料時間：{aqi_list[0]['publishtime']}")
        print()

    print(f"{'縣市':<6} {'測站':<8} {'AQI':>5} {'狀態':<12} {'PM2.5':>7} {'主要汙染物':<10}")
    print("-" * 70)

    for aqi in aqi_list:
        aqi_val = aqi['aqi'] if aqi['aqi'] != '' else '-'
        pm25 = aqi['pm25'] if aqi['pm25'] != '' else '-'
        pollutant = aqi['pollutant'] if aqi['pollutant'] != '' else '-'

        print(f"{aqi['emoji']} {aqi['county']:<5} {aqi['sitename']:<8} {aqi_val:>4} {aqi['status']:<12} {pm25:>6} {pollutant:<10}")

    print(f"\n  共 {len(aqi_list)} 個測站")

    # 顯示建議
    if aqi_list:
        worst = aqi_list[0]
        if worst['suggestion']:
            print(f"\n  💡 建議：{worst['suggestion']}")
    print()


# ============================================================
# 智慧建議功能
# ============================================================

def get_clothing_suggestion(temp_min, temp_max, rain_prob, comfort):
    """根據天氣狀況提供穿著建議"""
    suggestions = []

    # 溫度建議
    avg_temp = (temp_min + temp_max) / 2
    if avg_temp <= 10:
        suggestions.append("穿厚外套、毛衣、圍巾，注意保暖")
    elif avg_temp <= 15:
        suggestions.append("穿外套或薄毛衣，可搭配長褲")
    elif avg_temp <= 20:
        suggestions.append("穿薄外套或長袖上衣")
    elif avg_temp <= 25:
        suggestions.append("穿短袖或薄長袖，帶件薄外套備用")
    else:
        suggestions.append("穿輕薄透氣的衣物")

    # 降雨建議
    if rain_prob >= 70:
        suggestions.append("攜帶雨傘，建議穿防水鞋")
    elif rain_prob >= 50:
        suggestions.append("建議攜帶摺疊傘備用")
    elif rain_prob >= 30:
        suggestions.append("可帶輕便雨具以防萬一")

    # 舒適度建議
    if '悶熱' in comfort:
        suggestions.append("天氣悶熱，注意防曬補水")
    elif '寒冷' in comfort:
        suggestions.append("天氣寒冷，注意保暖")

    return suggestions


def get_activity_suggestion(weather, temp_min, temp_max, rain_prob, aqi=None):
    """根據天氣狀況提供活動建議"""
    suggestions = []

    # 戶外活動建議
    if rain_prob < 30 and '晴' in weather:
        suggestions.append("適合戶外活動、踏青、野餐")
    elif rain_prob < 50 and ('雲' in weather or '陰' in weather):
        suggestions.append("適合輕度戶外活動，但隨時注意天氣變化")
    elif rain_prob >= 50:
        suggestions.append("建議安排室內活動")

    # 溫度相關
    avg_temp = (temp_min + temp_max) / 2
    if avg_temp >= 28:
        suggestions.append("高溫天氣，避免長時間曝曬")
    elif avg_temp <= 15:
        suggestions.append("低溫天氣，戶外活動注意保暖")

    # AQI 相關
    if aqi is not None:
        try:
            aqi_val = int(aqi)
            if aqi_val > 150:
                suggestions.append("空氣品質不佳，敏感族群應避免戶外運動")
            elif aqi_val > 100:
                suggestions.append("空氣品質普通，敏感族群應減少戶外劇烈運動")
        except (ValueError, TypeError):
            pass

    return suggestions


def fetch_suggest_data(location):
    """取得用於建議的綜合資料"""
    normalized = normalize_location(location)
    result = {
        'weather': None,
        'aqi': None,
        'location': normalized
    }

    # 取得天氣預報
    try:
        weather_data = fetch_weather()
        weather_list = parse_weather_data(weather_data)
        # 從列表中找到指定縣市
        for w in weather_list:
            if w['location'] == normalized:
                # 確保溫度是數值
                w['min_temp'] = int(w['min_temp']) if str(w['min_temp']).isdigit() else 15
                w['max_temp'] = int(w['max_temp']) if str(w['max_temp']).isdigit() else 25
                w['rain_prob'] = int(w['rain_prob']) if str(w['rain_prob']).isdigit() else 0
                result['weather'] = w
                break
    except Exception as e:
        pass

    # 取得 AQI
    try:
        aqi_data = fetch_aqi()
        aqi_list = parse_aqi(aqi_data, location)
        if aqi_list:
            # 取該縣市的平均 AQI
            valid_aqi = [int(a['aqi']) for a in aqi_list if a['aqi'].isdigit()]
            if valid_aqi:
                result['aqi'] = sum(valid_aqi) // len(valid_aqi)
                result['aqi_status'] = aqi_list[0]['status']
    except Exception:
        pass

    return result


def print_suggestion(data):
    """輸出智慧建議"""
    print(f"\n{'='*70}")
    print(f"  {data['location']} 今日建議")
    print(f"{'='*70}\n")

    weather = data.get('weather')
    aqi = data.get('aqi')

    if not weather:
        print("  無法取得天氣資料")
        return

    # 天氣摘要
    print(f"  📍 {weather['location']}")
    print(f"  🌤️  天氣：{weather['weather']}")
    print(f"  🌡️  溫度：{weather['min_temp']}°C ~ {weather['max_temp']}°C")
    print(f"  🌧️  降雨機率：{weather['rain_prob']}%")
    print(f"  😊 舒適度：{weather['comfort']}")

    if aqi:
        aqi_emoji = '🟢' if aqi <= 50 else '🟡' if aqi <= 100 else '🟠' if aqi <= 150 else '🔴'
        print(f"  {aqi_emoji} AQI：{aqi}（{data.get('aqi_status', '')}）")

    # 穿著建議
    print(f"\n  👔 穿著建議")
    print("  " + "-" * 40)
    clothing = get_clothing_suggestion(
        weather['min_temp'], weather['max_temp'],
        weather['rain_prob'], weather['comfort']
    )
    for s in clothing:
        print(f"    • {s}")

    # 活動建議
    print(f"\n  🏃 活動建議")
    print("  " + "-" * 40)
    activities = get_activity_suggestion(
        weather['weather'], weather['min_temp'], weather['max_temp'],
        weather['rain_prob'], aqi
    )
    for s in activities:
        print(f"    • {s}")

    print()


def main():
    parser = argparse.ArgumentParser(
        description='台灣天氣查詢工具（使用中央氣象署 API）',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog='''
範例：
  python weather.py 台北           查詢台北市天氣（36 小時）
  python weather.py 台北 --week    查詢台北市一週預報
  python weather.py --all          查詢全台天氣概況
  python weather.py --now          即時觀測（全台測站）
  python weather.py --now 台北     即時觀測（指定縣市）
  python weather.py --earthquake   最近 5 筆地震報告
  python weather.py --alert        當前氣象警特報
  python weather.py --aqi          空氣品質指標（全台測站）
  python weather.py --aqi 台北     空氣品質指標（指定縣市）
  python weather.py --suggest 台北 今日穿搭與活動建議
  python weather.py --list         列出所有支援的縣市
        '''
    )
    parser.add_argument('location', nargs='?', help='縣市名稱（如：台北、新竹市）')
    parser.add_argument('--week', '-w', action='store_true', help='查詢一週天氣預報')
    parser.add_argument('--all', '-a', action='store_true', help='查詢全台天氣概況')
    parser.add_argument('--now', '-n', action='store_true', help='即時觀測資料（可搭配縣市名稱篩選）')
    parser.add_argument('--earthquake', '-e', action='store_true', help='查詢最近地震報告')
    parser.add_argument('--alert', action='store_true', help='查詢當前警特報')
    parser.add_argument('--aqi', action='store_true', help='空氣品質指標（可搭配縣市名稱篩選）')
    parser.add_argument('--suggest', '-s', action='store_true', help='今日穿搭與活動建議（需指定縣市）')
    parser.add_argument('--list', '-l', action='store_true', help='列出所有支援的縣市')

    args = parser.parse_args()

    if args.list:
        print("\n支援的縣市：")
        print("-"*30)
        cities = sorted(set(LOCATION_ALIASES.values()))
        for i, city in enumerate(cities, 1):
            print(f"  {i:2}. {city}")
        print()
        return

    # 即時觀測
    if args.now:
        data = fetch_observation()
        obs_list = parse_observation(data, args.location)
        print_observation(obs_list, args.location)
        return

    # 地震報告
    if args.earthquake:
        data = fetch_earthquake(limit=5)
        eq_list = parse_earthquake(data)
        print_earthquake(eq_list)
        return

    # 警特報
    if args.alert:
        data = fetch_alert()
        alert_list = parse_alert(data)
        print_alert(alert_list)
        return

    # 空氣品質
    if args.aqi:
        data = fetch_aqi()
        aqi_list = parse_aqi(data, args.location)
        print_aqi(aqi_list, args.location)
        return

    # 智慧建議
    if args.suggest:
        if not args.location:
            print("錯誤：--suggest 需要指定縣市名稱")
            print("範例：python weather.py --suggest 台北")
            return
        data = fetch_suggest_data(args.location)
        print_suggestion(data)
        return

    if args.all:
        data = fetch_weather()
        weather_list = parse_weather_data(data)
        print_summary(weather_list)
    elif args.location:
        normalized = normalize_location(args.location)

        if args.week:
            # 一週預報
            data = fetch_weekly_weather()
            weekly_data = parse_weekly_data(data, args.location)
            if weekly_data:
                print_weekly_weather(normalized, weekly_data)
            else:
                print(f"找不到「{args.location}」的一週預報資料")
                print("請使用 --list 查看支援的縣市")
        else:
            # 36 小時預報
            data = fetch_weather(normalized)
            weather_list = parse_weather_data(data)
            if weather_list:
                print_weather(weather_list)
            else:
                print(f"找不到「{args.location}」的天氣資料")
                print("請使用 --list 查看支援的縣市")
    else:
        parser.print_help()


if __name__ == '__main__':
    main()
