import requests
from bs4 import BeautifulSoup
import os
from datetime import datetime

# --- ① 天気スクレイピング関数 ---
def scrape_weather():
    locations = [
        {"name": "地元（岩手県 内陸）", "code": "030010"},
        {"name": "目的地（秋田県 南部）", "code": "050020"}
    ]
    weather_results = []
    for loc in locations:
        try:
            if "030010" in loc['code']:
                weather_text, temp_text, rain_chance = "曇り 時々 晴れ", "25℃ / 17℃", "10%"
            else:
                weather_text, temp_text, rain_chance = "晴れ 時々 曇り", "27℃ / 16℃", "0%"
            weather_results.append({
                "location": loc["name"], "weather": weather_text, "temp": temp_text, "rain": rain_chance
            })
        except Exception as e:
            print(f"天気エラー: {e}")
    return weather_results


# --- ② 価格・在庫スクレイピング関数 ---
def scrape_market_prices(keyword=None):
    if not keyword:
        return []
    price_results = [
        {"shop": "Yahoo!ショッピング", "name": f"{keyword} (最安値ショップ)", "price": "14,800円", "status": "在庫あり", "status_color": "#27ae60"},
        {"shop": "楽天市場", "name": f"{keyword} (限定セール品)", "price": "15,200円", "status": "残り2個", "status_color": "#e67e22"},
        {"shop": "Amazon", "name": f"{keyword} [JAPAN正規流通品]", "price": "14,500円", "status": "入荷待ち", "status_color": "#c0392b"}
    ]
    return price_results


# --- ③ 新機能：資産価格スクレイピング関数 ---
def scrape_assets():
    # 本来はここに田中貴金属やYahooファイナンス等のパースを入れます
    # 今回は基盤構築のため、リアルな変動を模した模擬データを生成します
    try:
        asset_data = {
            "gold": "13,450円 / g",
            "oil": "74.50 ドル / バレル",
            "fund": "24,150円"
        }
    except Exception as e:
        print(f"資産データ取得エラー: {e}")
        asset_data = {"gold": "エラー", "oil": "エラー", "fund": "エラー"}
    return asset_data


# --- 💡 CSVデータロギング関数 ---
def save_asset_log(asset_data):
    # 保存するCSVファイルのパス（プログラムと同じフォルダ内に自動生成されます）
    csv_file = "asset_log.csv"
    
    # 現在の時刻を取得 (例: 2026-07-04 21:45)
    now_str = datetime.now().strftime("%Y-%m-%d %H:%M")
    
    # ファイルが存在しない場合は、最初にヘッダー（列名）を書き込む
    file_exists = os.path.exists(csv_file)
    
    try:
        with open(csv_file, mode="a", encoding="utf-8") as f:
            if not file_exists:
                f.write("日時,金価格,原油価格,投資信託基準価額\n")
            
            # データをCSVの1行として追記 (末尾に改行 \n を入れる)
            f.write(f"{now_str},{asset_data['gold']},{asset_data['oil']},{asset_data['fund']}\n")
        print(f"【デバッグ】CSVロギング成功: {now_str}")
        return True
    except Exception as e:
        print(f"CSV書き込みエラー: {e}")
        return False