"""Research signal file for YOUR OWN strategy (prediction-market or weather-sensitive research).

This script only READS data and WRITES signals.csv and signals.json. It places no orders, talks to
no exchange and holds no exchange keys. Whatever you do with the file is your decision and your risk.

GetFixn sells data, not trading advice. Nothing here is investment advice. Forecasts can be wrong.
You are responsible for your own strategies and for following the rules of any exchange or market you use.

pip install requests
export GETFIXN_KEY=tfx_live_...
Cost per run: locations x ($0.05 + $0.0002). Forecast grades refresh 4 times a day.
"""
import csv
import json
import os
import sys
import time

import gf_client as gf

FIELDS = ["ts_utc", "label", "lat", "lon", "county", "state", "grade", "grade_score",
          "temperature_f", "alert_count", "alerts"]


def build(locs, window="24h"):
    g = {r["label"]: r for r in gf.grades(locs, window)}
    w = {r["label"]: r for r in gf.weather(locs)}
    ts = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
    rows = []
    for l in locs:
        gr, we = g[l["label"]], w[l["label"]]
        grade = gr.get("grade")
        alerts = we.get("alerts") or []
        rows.append({
            "ts_utc": ts, "label": l["label"], "lat": l["lat"], "lon": l["lon"],
            "county": gr.get("county"), "state": gr.get("state"), "grade": grade,
            "grade_score": gf.GRADES.index(grade) if grade in gf.GRADES else None,  # A=0 ... F=5
            "temperature_f": (we.get("current") or {}).get("temperature_f"),
            "alert_count": len(alerts), "alerts": json.dumps(alerts)})
    return rows


def write(rows, stem="signals"):
    with open(stem + ".json", "w") as f:
        json.dump(rows, f, indent=2)
    new = not os.path.exists(stem + ".csv")
    with open(stem + ".csv", "a", newline="") as f:  # CSV keeps history, one block per run
        w = csv.DictWriter(f, FIELDS)
        if new:
            w.writeheader()
        w.writerows(rows)


if __name__ == "__main__":
    try:
        rows = build(gf.load_locations(os.environ.get("LOCATIONS", "locations.json")), os.environ.get("WINDOW", "24h"))
    except gf.LowBalance as e:
        sys.exit("PAUSED: %s" % e)
    write(rows)
    print("wrote %d rows to signals.csv and signals.json" % len(rows))
