"""
IDX Scalping Dashboard - Local API Server
==========================================
Jalankan dulu:  pip install yfinance flask flask-cors
Lalu:           python api_server.py

Server jalan di http://localhost:5005
Dashboard HTML tinggal fetch ke sana.
"""

from flask import Flask, jsonify, request
from flask_cors import CORS
import yfinance as yf
import traceback

app = Flask(__name__)
CORS(app)  # izinkan dashboard HTML akses dari browser

# Cache sederhana di-memory agar tidak spam Yahoo Finance
_cache = {}
CACHE_TTL = 60  # detik

import time

def get_cached(key):
    if key in _cache:
        data, ts = _cache[key]
        if time.time() - ts < CACHE_TTL:
            return data
    return None

def set_cache(key, data):
    _cache[key] = (data, time.time())


def fetch_ticker(sym):
    """Ambil data OHLCV + info dari Yahoo Finance untuk saham IDX."""
    jk_sym = sym if sym.endswith(".JK") else sym + ".JK"
    cached = get_cached(jk_sym)
    if cached:
        return cached

    t = yf.Ticker(jk_sym)

    # Ambil 60 hari data harian untuk hitung indikator
    hist_1d = t.history(period="60d", interval="1d")
    # Ambil 5 hari data per-jam untuk grafik intraday
    hist_1h = t.history(period="5d", interval="1h")

    if hist_1d.empty:
        return None

    # Siapkan data harian
    closes_1d  = [round(float(x), 0) for x in hist_1d["Close"].tolist()]
    volumes_1d = [int(x) for x in hist_1d["Volume"].tolist()]
    dates_1d   = [str(d.date()) for d in hist_1d.index]

    # Siapkan data 1H (fallback ke daily jika kosong)
    if not hist_1h.empty:
        closes_1h  = [round(float(x), 0) for x in hist_1h["Close"].tolist()]
        volumes_1h = [int(x) for x in hist_1h["Volume"].tolist()]
        labels_1h  = [d.strftime("%d/%m %H:%M") for d in hist_1h.index]
    else:
        closes_1h  = closes_1d[-30:]
        volumes_1h = volumes_1d[-30:]
        labels_1h  = dates_1d[-30:]

    # Info nama perusahaan (opsional, sering timeout — fallback ke sym)
    try:
        info = t.fast_info
        name = getattr(info, "company_name", None) or sym
        currency = getattr(info, "currency", "IDR")
    except Exception:
        name = sym
        currency = "IDR"

    price_now  = closes_1d[-1]
    price_prev = closes_1d[-2] if len(closes_1d) > 1 else price_now
    pct_change = round((price_now - price_prev) / price_prev * 100, 2) if price_prev else 0

    result = {
        "symbol":       sym,
        "name":         name,
        "currency":     currency,
        "price":        price_now,
        "prev_close":   price_prev,
        "pct_change":   pct_change,
        "daily": {
            "closes":   closes_1d,
            "volumes":  volumes_1d,
            "dates":    dates_1d,
        },
        "hourly": {
            "closes":   closes_1h,
            "volumes":  volumes_1h,
            "labels":   labels_1h,
        },
    }

    set_cache(jk_sym, result)
    return result


@app.route("/quote/<sym>")
def quote(sym):
    sym = sym.upper().replace(".JK", "")
    try:
        data = fetch_ticker(sym)
        if data is None:
            return jsonify({"error": f"Ticker {sym} tidak ditemukan atau tidak ada data"}), 404
        return jsonify({"ok": True, "data": data})
    except Exception as e:
        traceback.print_exc()
        return jsonify({"error": str(e)}), 500


@app.route("/batch")
def batch():
    """
    GET /batch?syms=BBRI,BBCA,TLKM
    Fetch beberapa ticker sekaligus.
    """
    syms_raw = request.args.get("syms", "")
    syms = [s.strip().upper() for s in syms_raw.split(",") if s.strip()]
    if not syms:
        return jsonify({"error": "Parameter ?syms= wajib diisi"}), 400

    results = {}
    errors  = {}
    for sym in syms:
        try:
            data = fetch_ticker(sym)
            if data:
                results[sym] = data
            else:
                errors[sym] = "tidak ditemukan"
        except Exception as e:
            errors[sym] = str(e)

    return jsonify({"ok": True, "data": results, "errors": errors})


@app.route("/health")
def health():
    return jsonify({"status": "ok", "cache_keys": list(_cache.keys())})


if __name__ == "__main__":
    print("=" * 55)
    print("  IDX Scalping API Server")
    print("  http://localhost:5005")
    print("  Endpoints:")
    print("    GET /quote/BBRI")
    print("    GET /batch?syms=BBRI,BBCA,TLKM")
    print("    GET /health")
    print("=" * 55)
    app.run(port=5005, debug=False)
