"""
Board Snapshot — Market briefing dataset for CFO review.
Tickers: MSFT, GOOGL, NVDA
Macro: Real GDP, CPI
Output: board_snapshot.csv
"""

import os
import sys
import csv
from datetime import datetime

# Load .env manually (no dotenv dependency)
env_path = os.path.join(os.path.dirname(__file__), ".env")
if os.path.exists(env_path):
    with open(env_path) as f:
        for line in f:
            line = line.strip()
            if line and not line.startswith("#") and "=" in line:
                k, v = line.split("=", 1)
                os.environ.setdefault(k.strip(), v.strip())

from av_helper import av_get, throttle

TICKERS = ["MSFT", "GOOGL", "NVDA"]
OUTPUT = "board_snapshot.csv"
ROWS = []


def add_row(section, ticker, field, value):
    ROWS.append({"section": section, "ticker": ticker, "field": field, "value": value})


def safe_call(label, func, *args, **kwargs):
    """Wrap an API call; on failure, return None and log it."""
    try:
        result = func(*args, **kwargs)
        throttle()
        return result
    except Exception as e:
        print(f"  [WARN] {label}: {e}")
        return None


# ── 1. Per-ticker data ──────────────────────────────────────────────

for ticker in TICKERS:
    print(f"\n{'='*50}")
    print(f"  {ticker}")
    print(f"{'='*50}")

    # 1a. Latest quote
    print(f"  → Fetching quote...")
    data = safe_call(f"{ticker} quote", av_get, "GLOBAL_QUOTE", symbol=ticker)
    if data and "Global Quote" in data:
        q = data["Global Quote"]
        add_row("quote", ticker, "price", q.get("05. price", "N/A"))
        add_row("quote", ticker, "change", q.get("09. change", "N/A"))
        add_row("quote", ticker, "change_pct", q.get("10. change percent", "N/A"))
        add_row("quote", ticker, "volume", q.get("06. volume", "N/A"))
        add_row("quote", ticker, "trading_day", q.get("07. latest trading day", "N/A"))
    else:
        add_row("quote", ticker, "price", "API_ERROR")
        add_row("quote", ticker, "note", "Quote unavailable — possible rate limit")

    # 1b. ~30 daily closes
    print(f"  → Fetching daily series...")
    data = safe_call(f"{ticker} daily", av_get, "TIME_SERIES_DAILY", symbol=ticker, outputsize="compact")
    if data and "Time Series (Daily)" in data:
        ts = data["Time Series (Daily)"]
        dates_sorted = sorted(ts.keys(), reverse=True)[:30]
        for d in dates_sorted:
            add_row("daily_close", ticker, d, ts[d]["4. close"])
    else:
        add_row("daily_close", ticker, "error", "Daily series unavailable — possible rate limit")

    # 1c. RSI(14)
    print(f"  → Fetching RSI(14)...")
    data = safe_call(
        f"{ticker} RSI", av_get, "RSI",
        symbol=ticker, interval="daily", time_period="14", series_type="close",
    )
    if data and "Technical Analysis: RSI" in data:
        rsi_data = data["Technical Analysis: RSI"]
        latest_date = sorted(rsi_data.keys(), reverse=True)[0]
        add_row("rsi_14", ticker, f"RSI_14 ({latest_date})", rsi_data[latest_date]["RSI"])
    else:
        add_row("rsi_14", ticker, "error", "RSI unavailable — possible rate limit")

    # 1d. Company overview
    print(f"  → Fetching overview...")
    data = safe_call(f"{ticker} overview", av_get, "OVERVIEW", symbol=ticker)
    if data and "MarketCapitalization" in data:
        for field in [
            "MarketCapitalization", "PERatio", "EPS",
            "52WeekHigh", "52WeekLow", "Sector", "Industry",
            "Name", "Description",
        ]:
            val = data.get(field, "N/A")
            # Truncate long descriptions for CSV readability
            if field == "Description" and len(str(val)) > 200:
                val = str(val)[:200] + "..."
            add_row("overview", ticker, field, val)
    else:
        add_row("overview", ticker, "error", "Overview unavailable — possible rate limit")


# ── 2. Macro context ────────────────────────────────────────────────

print(f"\n{'='*50}")
print(f"  MACRO INDICATORS")
print(f"{'='*50}")

# 2a. Real GDP (annual)
print("  → Fetching Real GDP...")
data = safe_call("Real GDP", av_get, "REAL_GDP", interval="annual")
if data and "data" in data:
    for entry in data["data"][:5]:  # last 5 years
        add_row("macro_gdp", "US", entry["date"], entry["value"])
else:
    add_row("macro_gdp", "US", "error", "GDP data unavailable — possible rate limit")

# 2b. CPI
print("  → Fetching CPI...")
data = safe_call("CPI", av_get, "CPI", interval="monthly")
if data and "data" in data:
    for entry in data["data"][:12]:  # last 12 months
        add_row("macro_cpi", "US", entry["date"], entry["value"])
else:
    add_row("macro_cpi", "US", "error", "CPI data unavailable — possible rate limit")


# ── 3. Write CSV ────────────────────────────────────────────────────

out_path = os.path.join(os.path.dirname(__file__), OUTPUT)
with open(out_path, "w", newline="") as f:
    writer = csv.DictWriter(f, fieldnames=["section", "ticker", "field", "value"])
    writer.writeheader()
    writer.writerows(ROWS)

print(f"\n✓ Wrote {len(ROWS)} rows → {OUTPUT}")
print(f"  Generated: {datetime.now().strftime('%Y-%m-%d %H:%M')}")
print(f"  API calls used: {3*4 + 2} of 25 daily limit")
