import com.dukascopy.api.*;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Logs sudden "steps" in Dukascopy's XAU/USD price: the mid-price moving at least Threshold
 * within WindowMs. Research only - it never places orders and sends nothing anywhere.
 *
 * Output (in JForex's strategy files folder, shown in the console at start):
 *   duka_steps_YYYYMMDD.csv  - every step: tick time (UTC, ms), direction (LONG = up, SHORT = down), size, bid, ask
 *   duka_ticks_YYYYMMDD.csv  - every tick (optional), for re-running the analysis later
 *   duka_signals_YYYYMMDD.csv - predicted source signals (LONG/SHORT/FLAT), applying the source's rules:
 *                              1-minute minimum hold, 1-minute cooldown after FLAT, exit on an
 *                              opposite step, forced FLAT at the session end (21:00 UTC)
 * Steps and predicted signals are also printed in the JForex console.
 */
public class DukaStepLogger implements IStrategy {

    @Configurable("Step threshold (price)")
    public double threshold = 0.6;
    @Configurable("Step window (ms)")
    public int windowMs = 200;
    @Configurable("Min gap between steps (ms)")
    public int stepCooldownMs = 1000;
    @Configurable("Also log every tick")
    public boolean logTicks = true;
    @Configurable("Minimum hold before an exit (ms)")
    public int minHoldMs = 60000;
    @Configurable("Cooldown after FLAT before a new entry (ms)")
    public int flatCooldownMs = 60000;
    @Configurable("Session end hour UTC (forced FLAT, no entries until midnight; -1 = off)")
    public int sessionEndHourUtc = 21;

    private IConsole console;
    private File dir;
    private final ArrayDeque<double[]> window = new ArrayDeque<>();   // {tickTimeMs, mid}
    private long lastStepMs = 0;
    // predicted source position
    private int pos = 0;                 // +1 long, -1 short, 0 flat
    private long posSinceMs = 0, flatSinceMs = Long.MIN_VALUE / 2;
    private double entryPrice = 0;
    private int predTrades = 0; private double predPts = 0;
    private BufferedWriter sigCsv;
    private BufferedWriter stepCsv, tickCsv;
    private String csvDay = "";
    private long lastFlush = 0;
    private final SimpleDateFormat dayFmt = new SimpleDateFormat("yyyyMMdd", Locale.ROOT);
    private final SimpleDateFormat timeFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.ROOT);

    @Override
    public void onStart(IContext context) throws JFException {
        console = context.getConsole();
        dayFmt.setTimeZone(TimeZone.getTimeZone("UTC"));
        timeFmt.setTimeZone(TimeZone.getTimeZone("UTC"));
        dir = context.getFilesDir();
        Set<Instrument> instruments = new HashSet<>();
        instruments.add(Instrument.XAUUSD);
        context.setSubscribedInstruments(instruments, true);
        console.getOut().println("DukaStepLogger: step >= " + threshold + " within " + windowMs
                + " ms | min hold " + minHoldMs / 1000 + "s, cooldown " + flatCooldownMs / 1000 + "s, session end "
                + (sessionEndHourUtc < 0 ? "off" : sessionEndHourUtc + ":00 UTC") + " | files in " + dir.getAbsolutePath());
    }

    @Override
    public void onTick(Instrument instrument, ITick tick) throws JFException {
        if (instrument != Instrument.XAUUSD) return;
        long t = tick.getTime();
        double bid = tick.getBid(), ask = tick.getAsk(), mid = (bid + ask) / 2.0;

        if (logTicks) write(t, false, timeFmt.format(new Date(t)) + "," + bid + "," + ask);

        // forced FLAT at the session end
        if (pos != 0 && inClosedHours(t))
            goFlat(t, bid, ask, "session end", 0);

        window.addLast(new double[]{t, mid});
        // Keep the last tick from before the window as well: it is the price that was in force at the
        // window's start. Without it, a gap in ticks (e.g. 150 ms with no update) hides the step's start.
        while (window.size() > 1) {
            Iterator<double[]> it = window.iterator();
            it.next();
            if (t - (long) it.next()[0] >= windowMs) window.pollFirst(); else break;
        }

        double lo = Double.MAX_VALUE, hi = -Double.MAX_VALUE;
        for (double[] p : window) { lo = Math.min(lo, p[1]); hi = Math.max(hi, p[1]); }

        if (t - lastStepMs < stepCooldownMs) return;
        String dirName = null; double size = 0;
        if (mid - lo >= threshold) { dirName = "LONG"; size = mid - lo; }
        else if (hi - mid >= threshold) { dirName = "SHORT"; size = hi - mid; }
        if (dirName == null) return;

        lastStepMs = t;
        String line = String.format(Locale.ROOT, "%s,%s,%.2f,%.3f,%.3f", timeFmt.format(new Date(t)), dirName, size, bid, ask);
        write(t, true, line);
        window.clear();   // one step per burst

        // ---- apply the source's rules to this step ----
        int d = dirName.equals("LONG") ? 1 : -1;
        String action;
        if (pos == 0) {
            if (inClosedHours(t)) action = "ignored (session closed)";
            else if (t - flatSinceMs < flatCooldownMs)
                action = String.format(Locale.ROOT, "ignored (cooldown, %.0fs since FLAT)", (t - flatSinceMs) / 1000.0);
            else {
                pos = d; posSinceMs = t; entryPrice = d == 1 ? ask : bid;
                signal(t, d == 1 ? "LONG" : "SHORT", "step", size, bid, ask, 0, Double.NaN);
                action = "-> " + (d == 1 ? "LONG" : "SHORT");
            }
        } else if (d == pos) {
            action = "ignored (same direction as position)";
        } else if (t - posSinceMs < minHoldMs) {
            action = String.format(Locale.ROOT, "ignored (min hold, %.0fs held)", (t - posSinceMs) / 1000.0);
        } else {
            goFlat(t, bid, ask, "opposite step", size);
            action = "-> FLAT";
        }
        console.getOut().println("STEP " + line + "  " + action);
    }

    private boolean inClosedHours(long t) {
        if (sessionEndHourUtc < 0) return false;
        Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
        c.setTimeInMillis(t);
        return c.get(Calendar.HOUR_OF_DAY) >= sessionEndHourUtc;
    }

    private void goFlat(long t, double bid, double ask, String reason, double size) {
        double exit = pos == 1 ? bid : ask;
        double pts = pos * (exit - entryPrice);
        predTrades++; predPts += pts;
        signal(t, "FLAT", reason, size, bid, ask, (t - posSinceMs) / 1000.0, pts);
        pos = 0; flatSinceMs = t;
    }

    private void signal(long t, String sig, String reason, double size, double bid, double ask, double heldSec, double pts) {
        String line = String.format(Locale.ROOT, "%s,%s,%s,%.2f,%.3f,%.3f,%.0f,%s",
                timeFmt.format(new Date(t)), sig, reason, size, bid, ask, heldSec,
                Double.isNaN(pts) ? "" : String.format(Locale.ROOT, "%.2f", pts));
        try {
            write(t, false, null);                       // make sure today's files are open
            if (sigCsv != null) { sigCsv.write(line + "\n"); sigCsv.flush(); }
        } catch (IOException e) {
            console.getErr().println("Write failed: " + e);
        }
        String extra = sig.equals("FLAT")
                ? String.format(Locale.ROOT, " | trade %+.2f pts | today %d trades %+.2f pts (Dukascopy prices)", pts, predTrades, predPts)
                : "";
        console.getOut().println("SIGNAL " + line + extra);
    }

    private void write(long t, boolean step, String line) {
        try {
            String day = dayFmt.format(new Date(t));
            if (!day.equals(csvDay)) {
                closeFiles();
                File s = new File(dir, "duka_steps_" + day + ".csv");
                boolean sNew = !s.exists();
                stepCsv = new BufferedWriter(new FileWriter(s, true));
                if (sNew) stepCsv.write("Timestamp_UTC,Dir,Size,Bid,Ask\n");
                File g = new File(dir, "duka_signals_" + day + ".csv");
                boolean gNew = !g.exists();
                sigCsv = new BufferedWriter(new FileWriter(g, true));
                if (gNew) sigCsv.write("Timestamp_UTC,Signal,Reason,StepSize,Bid,Ask,HeldSec,Points\n");
                if (!day.equals(csvDay) && !csvDay.isEmpty()) { predTrades = 0; predPts = 0; }
                if (logTicks) {
                    File k = new File(dir, "duka_ticks_" + day + ".csv");
                    boolean kNew = !k.exists();
                    tickCsv = new BufferedWriter(new FileWriter(k, true));
                    if (kNew) tickCsv.write("Timestamp_UTC,Bid,Ask\n");
                }
                csvDay = day;
            }
            if (line == null) return;
            if (step) { stepCsv.write(line + "\n"); stepCsv.flush(); }
            else if (tickCsv != null) tickCsv.write(line + "\n");
            long now = System.currentTimeMillis();
            if (tickCsv != null && now - lastFlush > 1000) { tickCsv.flush(); lastFlush = now; }
        } catch (IOException e) {
            console.getErr().println("Write failed: " + e);
        }
    }

    private void closeFiles() {
        try {
            if (stepCsv != null) stepCsv.close();
            if (tickCsv != null) tickCsv.close();
            if (sigCsv != null) sigCsv.close();
        } catch (IOException ignored) { }
        stepCsv = null; tickCsv = null; sigCsv = null;
    }

    @Override public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) { }
    @Override public void onMessage(IMessage message) { }
    @Override public void onAccount(IAccount account) { }
    @Override public void onStop() { closeFiles(); }
}
