"""
Faithful Python port of the Pine indicator "Demand_Supply_Zones Lalan"
(3-candle buyer/seller zones, confirmation = Close, show last 3, no volatility filter).
READ-ONLY: pulls candles from Dhan, writes nothing, prints no token.

Run on the VM:   cd ~/pdmp && venv/bin/python zone_port.py
Optional args:   venv/bin/python zone_port.py 25700 CE 2026-11-23 45
                 (strike, CE/PE, expiry, days of history)

Port notes (all copied from the Pine source):
  * On every bar: detection first (bearish, then bullish), then the drawing/removal pass.
  * New zone = range of the MIDDLE candle (high[1], low[1]); start time = time[1].
  * A new zone is dropped if f_check_overlap says so. That check only runs when the
    list already holds MORE THAN ONE zone, and it misses a new zone that covers an old one.
  * The list keeps at most 20 zones per side (oldest dropped).
  * Removal pass walks newest -> oldest. Only the newest `show_last` zones are visited;
    a visited zone is removed when close is beyond it (bull: bottom > close, bear: top < close),
    and the loop STOPS after one removal.
  * Zones beyond the newest `show_last` stay in the list (hidden) and still count for overlap.
"""
import csv
import io
import os
import sys
import time
import urllib.request
from datetime import datetime, timedelta, timezone

IST = timezone(timedelta(hours=5, minutes=30))
CLIENT_ID_DEFAULT = "1000731429"
SCRIP_URL = "https://images.dhan.co/api-data/api-scrip-master.csv"

SHOW_LAST = 3
MAX_ZONES = 20


class Zone:
    __slots__ = ("top", "bottom", "start", "born")

    def __init__(self, top, bottom, start, born):
        self.top = top
        self.bottom = bottom
        self.start = start      # time of the middle candle (Pine barStart)
        self.born = born        # time of the bar on which the zone was detected


# ----------------------------------------------------------------------------- core logic
def pine_overlap(zones, top, bottom):
    """f_check_overlap exactly as written in Pine (only runs when size > 1)."""
    if len(zones) > 1:
        for z in zones:
            if (top < z.top and top > z.bottom) or (bottom > z.bottom and bottom < z.top):
                return True, z
    return False, None


def geometric_overlap(zones, top, bottom):
    """Any intersection at all (used only for reporting what the Pine check misses)."""
    for z in zones:
        if top > z.bottom and bottom < z.top:
            return z
    return None


def run_zones(bars, show_last=SHOW_LAST, confirm="Close"):
    """bars: list of dicts with t,o,h,l,c in time order. Returns (bull, bear, events, stats)."""
    bull, bear, events = [], [], []
    stats = dict(bull_formed=0, bull_rejected=0, bull_added_overlapping=0,
                 bear_formed=0, bear_rejected=0, bear_added_overlapping=0,
                 bull_removed=0, bear_removed=0)

    def add_zone(side, zones, b1, b, stat_prefix):
        z = Zone(b1["h"], b1["l"], b1["t"], b["t"])
        stats[stat_prefix + "_formed"] += 1
        rejected, other = pine_overlap(zones, z.top, z.bottom)
        if rejected:
            stats[stat_prefix + "_rejected"] += 1