// src/screens/data_mapping/DataMappingScreen_Data.cpp
//
// Catalog of supported wire schemas + pre-built broker/API mapping templates.
// Exposed via the accessor functions declared in DataMappingScreen_internal.h.

#include "screens/data_mapping/DataMappingScreen_internal.h"

namespace fincept::screens::data_mapping_internal {

const QList<SchemaInfo>& schemas() {
    static const QList<SchemaInfo> g = {
        {"OHLCV",
         "Open/High/Low/Close/Volume candlestick data",
         {
             {"symbol", "string", true, "Trading symbol"},
             {"timestamp", "datetime", true, "Bar timestamp"},
             {"open", "number", true, "Opening price"},
             {"high", "number", true, "Highest price"},
             {"low", "number", true, "Lowest price"},
             {"close", "number", true, "Closing price"},
             {"volume", "number", true, "Trading volume"},
             {"vwap", "number", false, "Volume weighted avg price"},
             {"trades", "number", false, "Number of trades"},
         }},
        {"QUOTE",
         "Real-time or delayed quote with bid/ask",
         {
             {"symbol", "string", true, "Trading symbol"},
             {"timestamp", "datetime", true, "Quote timestamp"},
             {"price", "number", true, "Last traded price"},
             {"bid", "number", false, "Best bid price"},
             {"ask", "number", false, "Best ask price"},
             {"bidSize", "number", false, "Bid quantity"},
             {"askSize", "number", false, "Ask quantity"},
             {"volume", "number", false, "Total volume"},
             {"change", "number", false, "Change from prev close"},
             {"changePercent", "number", false, "Percentage change"},
             {"open", "number", false, "Day open price"},
             {"high", "number", false, "Day high price"},
             {"low", "number", false, "Day low price"},
             {"previousClose", "number", false, "Previous close"},
         }},
        {"TICK",
         "Individual trade ticks",
         {
             {"symbol", "string", true, "Trading symbol"},
             {"timestamp", "datetime", true, "Trade timestamp"},
             {"price", "number", true, "Trade price"},
             {"quantity", "number", true, "Trade quantity"},
             {"side", "enum", false, "BUY/SELL/UNKNOWN"},
             {"tradeId", "string", false, "Unique trade ID"},
         }},
        {"ORDER",
         "Trading order",
         {
             {"orderId", "string", true, "Unique order ID"},
             {"symbol", "string", true, "Trading symbol"},
             {"side", "enum", true, "BUY/SELL"},
             {"type", "enum", true, "MARKET/LIMIT/STOP/STOP_LIMIT"},
             {"quantity", "number", true, "Order quantity"},
             {"filledQuantity", "number", false, "Filled quantity"},
             {"price", "number", false, "Limit price"},
             {"averagePrice", "number", false, "Average fill price"},
             {"status", "enum", true, "PENDING/OPEN/FILLED/CANCELLED"},
             {"timestamp", "datetime", true, "Placement timestamp"},
             {"exchange", "string", false, "Exchange name"},
         }},
        {"POSITION",
         "Open position in portfolio",
         {
             {"symbol", "string", true, "Trading symbol"},
             {"quantity", "number", true, "Position quantity"},
             {"averagePrice", "number", true, "Average entry price"},
             {"currentPrice", "number", true, "Current market price"},
             {"marketValue", "number", true, "Current market value"},
             {"costBasis", "number", true, "Total cost basis"},
             {"pnl", "number", true, "Unrealized P&L"},
             {"pnlPercent", "number", true, "P&L percentage"},
             {"exchange", "string", false, "Exchange name"},
         }},
        {"PORTFOLIO",
         "Portfolio summary",
         {
             {"totalValue", "number", true, "Total portfolio value"},
             {"cash", "number", true, "Available cash"},
             {"invested", "number", true, "Total invested"},
             {"marketValue", "number", true, "Market value of holdings"},
             {"pnl", "number", true, "Total unrealized P&L"},
             {"pnlPercent", "number", true, "Total P&L percentage"},
             {"dayPnl", "number", false, "Today's P&L"},
             {"timestamp", "datetime", true, "Snapshot timestamp"},
         }},
        {"INSTRUMENT",
         "Security/instrument master data",
         {
             {"symbol", "string", true, "Trading symbol"},
             {"name", "string", true, "Instrument name"},
             {"exchange", "string", true, "Exchange"},
             {"instrumentType", "enum", true, "EQUITY/FUTURES/OPTIONS/CURRENCY"},
             {"isin", "string", false, "ISIN code"},
             {"lotSize", "number", false, "Lot size"},
             {"tickSize", "number", false, "Min price movement"},
         }},
    };
    return g;
}

const QList<MappingTemplate>& templates() {
    static const QList<MappingTemplate> g = {
        // Free public APIs.

        {"coingecko_quote",
         "CoinGecko Coin Price → QUOTE",
         "Fetch real-time crypto prices from CoinGecko. Free, no API key required. "
         "Returns price, market cap, 24h volume, and change data.",
         "CoinGecko",
         "QUOTE",
         {"crypto", "coingecko", "free", "public"},
         true,
         "https://api.coingecko.com",
         "/api/v3/simple/"
         "price?ids=bitcoin&vs_currencies=usd&include_24hr_vol=true&include_24hr_change=true&include_last_updated_at="
         "true",
         "GET",
         "None",
         "Accept: application/json",
         "",
         "JSONPath",
         {{"symbol", "$.bitcoin", "", "bitcoin"},
          {"price", "$.bitcoin.usd", "", "0"},
          {"volume", "$.bitcoin.usd_24h_vol", "", "0"},
          {"changePercent", "$.bitcoin.usd_24h_change", "", "0"},
          {"timestamp", "$.bitcoin.last_updated_at", "unix_to_iso", ""}}},

        {"coingecko_ohlcv",
         "CoinGecko OHLC → OHLCV",
         "Fetch OHLC candlestick data for any crypto from CoinGecko. Free API. "
         "Returns 1/7/14/30/90/180/365 day candles. Array format: [timestamp, O, H, L, C].",
         "CoinGecko",
         "OHLCV",
         {"crypto", "coingecko", "ohlc", "candles", "free"},
         true,
         "https://api.coingecko.com",
         "/api/v3/coins/bitcoin/ohlc?vs_currency=usd&days=30",
         "GET",
         "None",
         "Accept: application/json",
         "",
         "JSONPath",
         {{"timestamp", "$[*][0]", "unix_ms_to_iso", ""},
          {"open", "$[*][1]", "", "0"},
          {"high", "$[*][2]", "", "0"},
          {"low", "$[*][3]", "", "0"},
          {"close", "$[*][4]", "", "0"},
          {"symbol", "", "", "bitcoin"}}},

        {"yahoo_quote",
         "Yahoo Finance Spark → QUOTE",
         "Fetch real-time stock quotes from Yahoo Finance. Free, no API key. "
         "Returns last price, volume, and market state for any symbol.",
         "Yahoo Finance",
         "QUOTE",
         {"stocks", "yahoo", "free", "public", "us"},
         true,
         "https://query1.finance.yahoo.com",
         "/v8/finance/spark?symbols=AAPL&range=1d&interval=1d",
         "GET",
         "None",
         "Accept: application/json\nUser-Agent: Mozilla/5.0",
         "",
         "JSONPath",
         {{"symbol", "$.spark.result[0].symbol", "", ""},
          {"price", "$.spark.result[0].response[0].meta.regularMarketPrice", "", "0"},
          {"previousClose", "$.spark.result[0].response[0].meta.previousClose", "", "0"},
          {"volume", "$.spark.result[0].response[0].meta.regularMarketVolume", "", "0"},
          {"timestamp", "$.spark.result[0].response[0].meta.regularMarketTime", "unix_to_iso", ""}}},

        {"binance_ohlcv",
         "Binance Klines → OHLCV",
         "Fetch candlestick/kline data from Binance. Free, no API key required for market data. "
         "Supports intervals: 1m, 3m, 5m, 15m, 30m, 1h, 4h, 1d, 1w, 1M.",
         "Binance",
         "OHLCV",
         {"crypto", "binance", "klines", "candles", "free"},
         true,
         "https://api.binance.com",
         "/api/v3/klines?symbol=BTCUSDT&interval=1h&limit=100",
         "GET",
         "None",
         "Accept: application/json",
         "",
         "JSONPath",
         {{"timestamp", "$[*][0]", "unix_ms_to_iso", ""},
          {"open", "$[*][1]", "to_number", "0"},
          {"high", "$[*][2]", "to_number", "0"},
          {"low", "$[*][3]", "to_number", "0"},
          {"close", "$[*][4]", "to_number", "0"},
          {"volume", "$[*][5]", "to_number", "0"},
          {"trades", "$[*][8]", "to_number", "0"},
          {"symbol", "", "", "BTCUSDT"}}},

        {"binance_quote",
         "Binance 24hr Ticker → QUOTE",
         "Fetch 24-hour price statistics from Binance. Free, no API key. "
         "Returns price, bid/ask, volume, and 24h change for any trading pair.",
         "Binance",
         "QUOTE",
         {"crypto", "binance", "ticker", "free"},
         true,
         "https://api.binance.com",
         "/api/v3/ticker/24hr?symbol=BTCUSDT",
         "GET",
         "None",
         "Accept: application/json",
         "",
         "JSONPath",
         {{"symbol", "$.symbol", "", ""},
          {"price", "$.lastPrice", "to_number", "0"},
          {"bid", "$.bidPrice", "to_number", "0"},
          {"ask", "$.askPrice", "to_number", "0"},
          {"bidSize", "$.bidQty", "to_number", "0"},
          {"askSize", "$.askQty", "to_number", "0"},
          {"volume", "$.volume", "to_number", "0"},
          {"change", "$.priceChange", "to_number", "0"},
          {"changePercent", "$.priceChangePercent", "to_number", "0"},
          {"open", "$.openPrice", "to_number", "0"},
          {"high", "$.highPrice", "to_number", "0"},
          {"low", "$.lowPrice", "to_number", "0"},
          {"previousClose", "$.prevClosePrice", "to_number", "0"}}},

        {"kraken_ohlcv",
         "Kraken OHLC → OHLCV",
         "Fetch OHLC data from Kraken. Free public endpoint, no API key required. "
         "Intervals: 1, 5, 15, 30, 60, 240, 1440, 10080, 21600 minutes.",
         "Kraken",
         "OHLCV",
         {"crypto", "kraken", "ohlc", "free"},
         true,
         "https://api.kraken.com",
         "/0/public/OHLC?pair=XBTUSD&interval=60",
         "GET",
         "None",
         "Accept: application/json",
         "",
         "JSONPath",
         {{"timestamp", "$.result.XXBTZUSD[*][0]", "unix_to_iso", ""},
          {"open", "$.result.XXBTZUSD[*][1]", "to_number", "0"},
          {"high", "$.result.XXBTZUSD[*][2]", "to_number", "0"},
          {"low", "$.result.XXBTZUSD[*][3]", "to_number", "0"},
          {"close", "$.result.XXBTZUSD[*][4]", "to_number", "0"},
          {"vwap", "$.result.XXBTZUSD[*][5]", "to_number", "0"},
          {"volume", "$.result.XXBTZUSD[*][6]", "to_number", "0"},
          {"trades", "$.result.XXBTZUSD[*][7]", "to_number", "0"},
          {"symbol", "", "", "XBTUSD"}}},

        // API key required (free tier).

        {"alphavantage_ohlcv",
         "Alpha Vantage Intraday → OHLCV",
         "Fetch intraday OHLCV from Alpha Vantage. Free tier: 25 requests/day. "
         "Intervals: 1min, 5min, 15min, 30min, 60min. Set your API key in AUTH VALUE.",
         "Alpha Vantage",
         "OHLCV",
         {"stocks", "alphavantage", "intraday", "free-tier"},
         true,
         "https://www.alphavantage.co",
         "/query?function=TIME_SERIES_INTRADAY&symbol=IBM&interval=5min&apikey=YOUR_KEY",
         "GET",
         "API Key",
         "Accept: application/json",
         "",
         "JSONPath",
         {{"timestamp", "$.['Time Series (5min)'].*~", "", ""},
          {"open", "$.['Time Series (5min)'].*.['1. open']", "to_number", "0"},
          {"high", "$.['Time Series (5min)'].*.['2. high']", "to_number", "0"},
          {"low", "$.['Time Series (5min)'].*.['3. low']", "to_number", "0"},
          {"close", "$.['Time Series (5min)'].*.['4. close']", "to_number", "0"},
          {"volume", "$.['Time Series (5min)'].*.['5. volume']", "to_number", "0"},
          {"symbol", "", "", "IBM"}}},

        {"twelvedata_ohlcv",
         "Twelve Data Time Series → OHLCV",
         "Fetch OHLCV time series from Twelve Data. Free tier: 800 requests/day. "
         "Supports stocks, forex, crypto. Set API key in AUTH VALUE field.",
         "Twelve Data",
         "OHLCV",
         {"stocks", "forex", "crypto", "twelvedata", "free-tier"},
         true,
         "https://api.twelvedata.com",
         "/time_series?symbol=AAPL&interval=1h&outputsize=30&apikey=YOUR_KEY",
         "GET",
         "API Key",
         "Accept: application/json",
         "",
         "JSONPath",
         {{"timestamp", "$.values[*].datetime", "", ""},
          {"open", "$.values[*].open", "to_number", "0"},
          {"high", "$.values[*].high", "to_number", "0"},
          {"low", "$.values[*].low", "to_number", "0"},
          {"close", "$.values[*].close", "to_number", "0"},
          {"volume", "$.values[*].volume", "to_number", "0"},
          {"symbol", "$.meta.symbol", "", ""}}},

        {"finnhub_quote",
         "Finnhub Quote → QUOTE",
         "Fetch real-time stock quote from Finnhub. Free tier: 60 calls/min. "
         "Returns current price, change, high/low, open, previous close. Set API key in AUTH VALUE.",
         "Finnhub",
         "QUOTE",
         {"stocks", "finnhub", "free-tier", "us"},
         true,
         "https://finnhub.io",
         "/api/v1/quote?symbol=AAPL&token=YOUR_KEY",
         "GET",
         "API Key",
         "Accept: application/json",
         "",
         "JSONPath",
         {{"price", "$.c", "", "0"},
          {"change", "$.d", "", "0"},
          {"changePercent", "$.dp", "", "0"},
          {"high", "$.h", "", "0"},
          {"low", "$.l", "", "0"},
          {"open", "$.o", "", "0"},
          {"previousClose", "$.pc", "", "0"},
          {"timestamp", "$.t", "unix_to_iso", ""},
          {"symbol", "", "", "AAPL"}}},

        {"coinmarketcap_quote",
         "CoinMarketCap Latest → QUOTE",
         "Fetch latest crypto quotes from CoinMarketCap. Free tier: 10,000 calls/month. "
         "Returns price, volume, market cap, and 24h change. Set API key in AUTH VALUE.",
         "CoinMarketCap",
         "QUOTE",
         {"crypto", "coinmarketcap", "free-tier"},
         true,
         "https://pro-api.coinmarketcap.com",
         "/v1/cryptocurrency/quotes/latest?symbol=BTC&convert=USD",
         "GET",
         "API Key",
         "Accept: application/json\nX-CMC_PRO_API_KEY: YOUR_KEY",
         "",
         "JSONPath",
         {{"symbol", "$.data.BTC.symbol", "", ""},
          {"price", "$.data.BTC.quote.USD.price", "", "0"},
          {"volume", "$.data.BTC.quote.USD.volume_24h", "", "0"},
          {"change", "$.data.BTC.quote.USD.percent_change_24h", "", "0"},
          {"changePercent", "$.data.BTC.quote.USD.percent_change_24h", "", "0"},
          {"timestamp", "$.data.BTC.quote.USD.last_updated", "", ""}}},

        // Global broker APIs.

        {"alpaca_ohlcv",
         "Alpaca Bars → OHLCV",
         "Fetch historical bar data from Alpaca Markets. Free paper trading account available. "
         "Set API key as 'APCA-API-KEY-ID' and secret as 'APCA-API-SECRET-KEY' in headers.",
         "Alpaca",
         "OHLCV",
         {"stocks", "alpaca", "bars", "us"},
         true,
         "https://data.alpaca.markets",
         "/v2/stocks/AAPL/bars?timeframe=1Hour&start=2024-03-01&limit=100",
         "GET",
         "API Key",
         "Accept: application/json\nAPCA-API-KEY-ID: YOUR_KEY\nAPCA-API-SECRET-KEY: YOUR_SECRET",
         "",
         "JSONPath",
         {{"timestamp", "$.bars[*].t", "", ""},
          {"open", "$.bars[*].o", "", "0"},
          {"high", "$.bars[*].h", "", "0"},
          {"low", "$.bars[*].l", "", "0"},
          {"close", "$.bars[*].c", "", "0"},
          {"volume", "$.bars[*].v", "", "0"},
          {"vwap", "$.bars[*].vw", "", "0"},
          {"trades", "$.bars[*].n", "", "0"},
          {"symbol", "$.symbol", "", "AAPL"}}},

        {"alpaca_positions",
         "Alpaca Positions → POSITION",
         "Fetch open positions from Alpaca. Works with paper or live accounts. "
         "Set API credentials in headers.",
         "Alpaca",
         "POSITION",
         {"stocks", "alpaca", "positions", "us"},
         true,
         "https://paper-api.alpaca.markets",
         "/v2/positions",
         "GET",
         "API Key",
         "Accept: application/json\nAPCA-API-KEY-ID: YOUR_KEY\nAPCA-API-SECRET-KEY: YOUR_SECRET",
         "",
         "JSONPath",
         {{"symbol", "$[*].symbol", "", ""},
          {"quantity", "$[*].qty", "to_number", "0"},
          {"averagePrice", "$[*].avg_entry_price", "to_number", "0"},
          {"currentPrice", "$[*].current_price", "to_number", "0"},
          {"marketValue", "$[*].market_value", "to_number", "0"},
          {"costBasis", "$[*].cost_basis", "to_number", "0"},
          {"pnl", "$[*].unrealized_pl", "to_number", "0"},
          {"pnlPercent", "$[*].unrealized_plpc", "to_number", "0"},
          {"exchange", "$[*].exchange", "", ""}}},

        {"tradier_quote",
         "Tradier Quote → QUOTE",
         "Fetch stock quotes from Tradier. Free sandbox available. "
         "Set Bearer token in AUTH VALUE. Use sandbox URL for testing.",
         "Tradier",
         "QUOTE",
         {"stocks", "tradier", "us", "options"},
         true,
         "https://sandbox.tradier.com",
         "/v1/markets/quotes?symbols=AAPL",
         "GET",
         "Bearer Token",
         "Accept: application/json",
         "",
         "JSONPath",
         {{"symbol", "$.quotes.quote.symbol", "", ""},
          {"price", "$.quotes.quote.last", "", "0"},
          {"bid", "$.quotes.quote.bid", "", "0"},
          {"ask", "$.quotes.quote.ask", "", "0"},
          {"volume", "$.quotes.quote.volume", "", "0"},
          {"change", "$.quotes.quote.change", "", "0"},
          {"changePercent", "$.quotes.quote.change_percentage", "", "0"},
          {"open", "$.quotes.quote.open", "", "0"},
          {"high", "$.quotes.quote.high", "", "0"},
          {"low", "$.quotes.quote.low", "", "0"},
          {"previousClose", "$.quotes.quote.prevclose", "", "0"}}},

        // Macro / economic data.

        {"dbnomics_ohlcv",
         "DBnomics Series → OHLCV",
         "Fetch economic time series from DBnomics. Free, no API key. "
         "Access 100M+ series from ECB, Fed, World Bank, IMF. Replace provider/dataset/series in endpoint.",
         "DBnomics",
         "OHLCV",
         {"economics", "macro", "dbnomics", "free"},
         true,
         "https://api.db.nomics.world",
         "/v22/series/IMF/WEO:2024-04/USA.NGDP_RPCH.pcent_change?observations=1",
         "GET",
         "None",
         "Accept: application/json",
         "",
         "JSONPath",
         {{"timestamp", "$.series.docs[0].period", "", ""},
          {"close", "$.series.docs[0].value", "", "0"},
          {"symbol", "$.series.docs[0].series_code", "", ""}}},
    };
    return g;
}

} // namespace fincept::screens::data_mapping_internal
