'''
streamlit run streamlit_app.py

'''
"""
AutoTradeManager Dashboard — Clean UI + Full Class Logic
Author: Prasad | AutoTradeManager
"""

import streamlit as st
import pandas as pd
import sqlite3
from datetime import datetime, date
import io
import plotly.express as px

# ==================== CONFIGURATION ==================== #
DB_FILE                     = "trade_manager.db"
DEFAULT_CAPITAL             = 10000.0
DEFAULT_RISK_PCT            = 1.0
DEFAULT_MAX_DRAWDOWN_PCT    = 3.0
DEFAULT_MAX_PROFIT_PCT      = 5.0
MAX_OPEN_TRADES             = 3
MAX_LOSS_TRADES             = 1
MAX_TARGET_TRADES           = 2
# ======================================================= #

st.set_page_config(page_title="AutoTradeManager Dashboard", layout="wide")
st.title("AutoTradeManager Dashboard")
st.caption("Full control: create/close trades, CSV import/export, SQL console, settings")

st.markdown("""
<style>
    #MainMenu {visibility: hidden;}
    footer {visibility: hidden;}
    .stDeployButton {display:none;}
</style>
""", unsafe_allow_html=True)

# ====================== AutoTradeManager Class ======================
class AutoTradeManager:
    def __init__(self):
        self.db_file = DB_FILE
        self.default_capital = DEFAULT_CAPITAL
        self.default_risk_pct = DEFAULT_RISK_PCT
        self.max_drawdown_pct = DEFAULT_MAX_DRAWDOWN_PCT
        self.max_profit_pct = DEFAULT_MAX_PROFIT_PCT
        self.max_open_trades = MAX_OPEN_TRADES
        self.max_loss_trades = MAX_LOSS_TRADES
        self.max_target_trades = MAX_TARGET_TRADES

        self.init_db()
        self.ensure_today_row()
        self.load_stats()

    def get_conn(self):
        return sqlite3.connect(self.db_file, check_same_thread=False)

    def init_db(self):
        with self.get_conn() as conn:
            cur = conn.cursor()
            cur.execute("""CREATE TABLE IF NOT EXISTS open_trades (
                id INTEGER PRIMARY KEY AUTOINCREMENT, symbol TEXT, entry REAL, qty INTEGER,
                stop REAL, target REAL, lot_size INTEGER, direction TEXT, note TEXT, opened_at TEXT)""")
            cur.execute("""CREATE TABLE IF NOT EXISTS trade_log (
                id INTEGER PRIMARY KEY AUTOINCREMENT, symbol TEXT, entry REAL, exit REAL, qty INTEGER,
                pnl REAL, pnl_percent REAL, direction TEXT, note TEXT, closed_at TEXT,
                stop_loss REAL, target REAL, lot_size INTEGER, position_size INTEGER,
                rr REAL, outcome TEXT, capital_after REAL, daily_gain_loss REAL, daily_gain_loss_percent REAL)""")
            cur.execute("""CREATE TABLE IF NOT EXISTS daily_stats (
                date TEXT PRIMARY KEY, initial_capital REAL, capital REAL, daily_trades INTEGER,
                daily_gain_trades INTEGER, daily_loss_trades INTEGER, daily_gain_amount REAL,
                daily_loss_amount REAL, trading_halted INTEGER DEFAULT 0, carry_forward INTEGER DEFAULT 1,
                max_drawdown_pct REAL, max_profit_pct REAL)""")
            conn.commit()

    def ensure_today_row(self):
        td = date.today().strftime("%Y-%m-%d")
        with self.get_conn() as conn:
            cur = conn.cursor()
            cur.execute("SELECT 1 FROM daily_stats WHERE date = ?", (td,))
            if cur.fetchone(): return
            cur.execute("SELECT capital, carry_forward FROM daily_stats ORDER BY date DESC LIMIT 1")
            prev = cur.fetchone()
            initial = self.default_capital
            if prev and prev[1]: initial = float(prev[0]) if prev[0] else initial
            cur.execute("""INSERT OR REPLACE INTO daily_stats
                (date, initial_capital, capital, daily_trades, daily_gain_trades, daily_loss_trades,
                 daily_gain_amount, daily_loss_amount, trading_halted, carry_forward,
                 max_drawdown_pct, max_profit_pct)
                VALUES (?, ?, ?, 0, 0, 0, 0.0, 0.0, 0, 1, ?, ?)""",
                (td, initial, initial, self.max_drawdown_pct, self.max_profit_pct))
            conn.commit()

    def load_stats(self):
        self.ensure_today_row()
        with self.get_conn() as conn:
            cur = conn.cursor()
            td = date.today().strftime("%Y-%m-%d")
            cur.execute("SELECT * FROM daily_stats WHERE date = ?", (td,))
            row = cur.fetchone()
            cols = [d[0] for d in cur.description]
            stats = dict(zip(cols, row))
            self.initial_capital = float(stats.get("initial_capital", self.default_capital))
            self.capital = float(stats.get("capital", self.initial_capital))
            self.daily_trades = int(stats.get("daily_trades", 0))
            self.daily_gain_trades = int(stats.get("daily_gain_trades", 0))
            self.daily_loss_trades = int(stats.get("daily_loss_trades", 0))
            self.daily_gain_amount = float(stats.get("daily_gain_amount", 0.0))
            self.daily_loss_amount = float(stats.get("daily_loss_amount", 0.0))
            self.trading_halted = bool(stats.get("trading_halted", 0))
            self.carry_forward = bool(stats.get("carry_forward", 1))
            self.max_drawdown_pct = float(stats.get("max_drawdown_pct", self.max_drawdown_pct))
            self.max_profit_pct = float(stats.get("max_profit_pct", self.max_profit_pct))
            self.risk_pct = self.default_risk_pct

    def update_stats(self, updates):
        td = date.today().strftime("%Y-%m-%d")
        with self.get_conn() as conn:
            cur = conn.cursor()
            clause = ", ".join([f"{k} = ?" for k in updates])
            params = list(updates.values()) + [td]
            cur.execute(f"UPDATE daily_stats SET {clause} WHERE date = ?", params)
            conn.commit()
            self.load_stats()

    def count_open_trades(self):
        with self.get_conn() as conn:
            cur = conn.cursor()
            cur.execute("SELECT COUNT(*) FROM open_trades")
            return cur.fetchone()[0]

    def calc_qty(self, entry, stop):
        risk = self.capital * (self.risk_pct / 100)
        tick_risk = abs(entry - stop)
        return max(int(risk // tick_risk), 0) if tick_risk > 0 else 0

    def can_add_trade(self):
        open_trades = self.count_open_trades()
        wins = self.daily_gain_trades
        losses = self.daily_loss_trades
        if open_trades >= self.max_open_trades:
            return False, f"Max open trades ({open_trades}/{self.max_open_trades})"
        if losses + open_trades >= self.max_loss_trades:
            return False, f"Loss breach risk ({losses}+{open_trades} ≥ {self.max_loss_trades})"
        if wins + open_trades >= self.max_target_trades:
            return False, f"Target reached ({wins}+{open_trades} ≥ {self.max_target_trades})"
        return True, f"OK — Open: {open_trades}, Wins: {wins}, Losses: {losses}"

    def add_trade(self, symbol, entry, stop, target, lot_size=None, note=""):
        if self.trading_halted:
            return False, "Trading halted today."

        allowed, msg = self.can_add_trade()
        if not allowed:
            return False, msg

        direction = "LONG" if target > entry else "SHORT"
        qty = self.calc_qty(entry, stop)
        if qty <= 0:
            return False, "Qty=0. Invalid risk."

        profit = abs(target - entry)
        loss = abs(entry - stop)
        rr = round(profit / loss, 2) if loss > 0 else 0

        opened_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        with self.get_conn() as conn:
            cur = conn.cursor()
            cur.execute("""INSERT INTO open_trades
                (symbol, entry, qty, stop, target, lot_size, direction, note, opened_at)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""",
                (symbol.upper(), entry, qty, stop, target, lot_size, direction, note, opened_at))
            conn.commit()

        self.daily_trades += 1
        self.update_stats({"daily_trades": self.daily_trades})
        return True, f"{direction} {symbol} added. Qty: {qty} | RR: {rr}:1"

    def close_trade(self, trade_id, exit_price):
        with self.get_conn() as conn:
            cur = conn.cursor()
            cur.execute("SELECT * FROM open_trades WHERE id = ?", (trade_id,))
            row = cur.fetchone()
            if not row: return False, "Trade not found."
            cols = [d[0] for d in cur.description]
            trade = dict(zip(cols, row))

        entry, qty, direction = trade["entry"], trade["qty"], trade["direction"]
        pnl = (exit_price - entry) * qty if direction == "LONG" else (entry - exit_price) * qty
        self.capital = round(self.capital + pnl, 2)

        if pnl > 0:
            self.daily_gain_trades += 1
            self.daily_gain_amount += pnl
        elif pnl < 0:
            self.daily_loss_trades += 1
            self.daily_loss_amount += abs(pnl)
        self.daily_trades += 1

        closed_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        position_size = entry * qty
        rr = abs((exit_price - entry) / (entry - trade["stop"])) if trade["stop"] and (entry - trade["stop"]) != 0 else 0
        outcome = "WIN" if pnl > 0 else "LOSS" if pnl < 0 else "BE"

        # Calculate daily net
        daily_net = self.daily_gain_amount - self.daily_loss_amount
        daily_net_pct = (daily_net / self.initial_capital * 100) if self.initial_capital > 0 else 0

        with self.get_conn() as conn:
            cur = conn.cursor()
            cur.execute("""INSERT INTO trade_log
                (symbol, entry, exit, qty, pnl, pnl_percent, direction, note, closed_at,
                 stop_loss, target, lot_size, position_size, rr, outcome, capital_after,
                 daily_gain_loss, daily_gain_loss_percent)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""", (
                trade["symbol"], entry, exit_price, qty, pnl,
                round(pnl / position_size * 100, 2) if position_size > 0 else 0,
                direction, trade["note"], closed_at,
                trade["stop"], trade["target"], trade["lot_size"], position_size,
                round(rr, 2), outcome, self.capital,
                daily_net, daily_net_pct
            ))
            cur.execute("DELETE FROM open_trades WHERE id = ?", (trade_id,))
            conn.commit()

        self.update_stats({
            "capital": self.capital,
            "daily_trades": self.daily_trades,
            "daily_gain_trades": self.daily_gain_trades,
            "daily_loss_trades": self.daily_loss_trades,
            "daily_gain_amount": self.daily_gain_amount,
            "daily_loss_amount": self.daily_loss_amount
        })
        self.evaluate_auto_stop()
        return True, f"Closed: {outcome} | P&L: ₹{pnl:,.2f} | Capital: ₹{self.capital:,.2f}"

    def evaluate_auto_stop(self):
        net = self.daily_gain_amount - self.daily_loss_amount
        net_pct = (net / self.initial_capital * 100) if self.initial_capital else 0
        drawdown = ((self.initial_capital - self.capital) / self.initial_capital * 100)

        halted = False
        if drawdown >= self.max_drawdown_pct > 0:
            halted = True
        elif net_pct >= self.max_profit_pct > 0:
            halted = True

        if halted != self.trading_halted:
            self.trading_halted = halted
            self.update_stats({"trading_halted": int(halted)})

    def reset_db(self):
        with self.get_conn() as conn:
            cur = conn.cursor()
            for table in ["open_trades", "trade_log", "daily_stats"]:
                cur.execute(f"DROP TABLE IF EXISTS {table}")
            conn.commit()
        self.init_db()
        self.load_stats()
        return "Database reset."

    def ascii_bar(self, value, max_abs, width=30):
        if max_abs == 0: return "│"
        half = width // 2
        scaled = int(abs(value) / max_abs * half) if max_abs else 0
        left = "█" * scaled if value < 0 else " " * scaled
        right = "█" * scaled if value > 0 else " " * scaled
        return f"{left}│{right}"

# ====================== Streamlit UI (Your Clean Style) ======================
def main():
    if 'atm' not in st.session_state:
        st.session_state.atm = AutoTradeManager()

    atm = st.session_state.atm

    menu = st.sidebar.selectbox("Menu", [
        "Dashboard", "Add Trade", "Close Trade", "Import/Export", "Reports", "SQL Console", "Settings"
    ])

    # Quick Metrics
    with atm.get_conn() as conn:
        open_df = pd.read_sql("SELECT * FROM open_trades ORDER BY id DESC", conn)
        log_df = pd.read_sql("SELECT * FROM trade_log ORDER BY id DESC", conn)
        wins = len(log_df[log_df["outcome"] == "WIN"]) if not log_df.empty else 0
        loss = len(log_df[log_df["outcome"] == "LOSS"]) if not log_df.empty else 0

    col1, col2, col3, col4= st.columns(4)
    col1.metric("Open Trades", len(open_df))
    col2.metric("Wins", wins)
    col3.metric("Loss", loss)
    col4.metric("Current Capital", f"₹{atm.capital:,.2f}")

    # -------------------------------
    # Dashboard
    # -------------------------------
    if menu == "Dashboard":
        st.header("Dashboard")
        st.subheader("Open Trades")
        st.dataframe(open_df, use_container_width=True)

        st.subheader("Recent Trades (log)")
        st.dataframe(log_df.head(200), use_container_width=True)

        with atm.get_conn() as conn:
            ds_full = pd.read_sql("SELECT * FROM daily_stats ORDER BY date DESC", conn)
        st.subheader("Daily Stats")
        st.dataframe(ds_full, use_container_width=True)

        st.subheader("Equity Curve")
        if not ds_full.empty:
            fig = px.line(ds_full.sort_values("date"), x="date", y="capital", title="Equity Curve", markers=True)
            st.plotly_chart(fig, use_container_width=True)

        st.subheader("Daily PnL")
        if not ds_full.empty and "daily_gain_loss" not in ds_full.columns:
            ds_full["daily_gain_loss"] = ds_full["daily_gain_amount"] - ds_full["daily_loss_amount"]
        if not ds_full.empty:
            fig2 = px.bar(ds_full.sort_values("date"), x="date", y="daily_gain_loss", title="Daily PnL")
            st.plotly_chart(fig2, use_container_width=True)

 
    # --------------------------------------------------------------
    #  Add Trade – FIXED LAYOUT
    # --------------------------------------------------------------
    elif menu == "Add Trade":
        st.subheader("Add New Trade")

        if atm.trading_halted:
            st.error("Trading halted today.")
        else:
            allowed, msg = atm.can_add_trade()
            st.caption(msg)

        # -------------------------------------------------
        # 1. STOCK SELECTOR – full width dropdown
        # -------------------------------------------------
        stock_list = ["Enter Manually", "360ONE", "3MINDIA", "ABB", "ACC", "ACMESOLAR", "AIAENG", "APLAPOLLO", "AUBANK", "AWL", "AADHARHFC", "AARTIIND", "AAVAS", "ABBOTINDIA", "ACE", "ADANIENSOL", "ADANIENT", "ADANIGREEN", "ADANIPORTS", "ADANIPOWER", "ATGL", "ABCAPITAL", "ABFRL", "ABLBL", "ABREL", "ABSLAMC", "AEGISLOG", "AEGISVOPAK", "AFCONS", "AFFLE", "AJANTPHARM", "AKUMS", "AKZOINDIA", "APLLTD", "ALKEM", "ALKYLAMINE", "ALOKINDS", "ARE&M", "AMBER", "AMBUJACEM", "ANANDRATHI", "ANANTRAJ", "ANGELONE", "APARINDS", "APOLLOHOSP", "APOLLOTYRE", "APTUS", "ASAHIINDIA", "ASHOKLEY", "ASIANPAINT", "ASTERDM", "ASTRAZEN", "ASTRAL", "ATHERENERG", "ATUL", "AUROPHARMA", "AIIL", "DMART", "AXISBANK", "BASF", "BEML", "BLS", "BSE", "BAJAJ-AUTO", "BAJFINANCE", "BAJAJFINSV", "BAJAJHLDNG", "BAJAJHFL", "BALKRISIND", "BALRAMCHIN", "BANDHANBNK", "BANKBARODA", "BANKINDIA", "MAHABANK", "BATAINDIA", "BAYERCROP", "BERGEPAINT", "BDL", "BEL", "BHARATFORG", "BHEL", "BPCL", "BHARTIARTL", "BHARTIHEXA", "BIKAJI", "BIOCON", "BSOFT", "BLUEDART", "BLUEJET", "BLUESTARCO", "BBTC", "BOSCHLTD", "FIRSTCRY", "BRIGADE", "BRITANNIA", "MAPMYINDIA", "CCL", "CESC", "CGPOWER", "CRISIL", "CAMPUS", "CANFINHOME", "CANBK", "CAPLIPOINT", "CGCL", "CARBORUNIV", "CASTROLIND", "CEATLTD", "CENTRALBK", "CDSL", "CENTURYPLY", "CERA", "CHALET", "CHAMBLFERT", "CHENNPETRO", "CHOICEIN", "CHOLAHLDNG", "CHOLAFIN", "CIPLA", "CUB", "CLEAN", "COALINDIA", "COCHINSHIP", "COFORGE", "COHANCE", "COLPAL", "CAMS", "CONCORDBIO", "CONCOR", "COROMANDEL", "CRAFTSMAN", "CREDITACC", "CROMPTON", "CUMMINSIND", "CYIENT", "DCMSHRIRAM", "DLF", "DOMS", "DABUR", "DALBHARAT", "DATAPATTNS", "DEEPAKFERT", "DEEPAKNTR", "DELHIVERY", "DEVYANI", "DIVISLAB", "DIXON", "AGARWALEYE", "LALPATHLAB", "DRREDDY", "EIDPARRY", "EIHOTEL", "EICHERMOT", "ELECON", "ELGIEQUIP", "EMAMILTD", "EMCURE", "ENDURANCE", "ENGINERSIN", "ERIS", "ESCORTS", "ETERNAL", "EXIDEIND", "NYKAA", "FEDERALBNK", "FACT", "FINCABLES", "FINPIPE", "FSL", "FIVESTAR", "FORCEMOT", "FORTIS", "GAIL", "GVT&D", "GMRAIRPORT", "GRSE", "GICRE", "GILLETTE", "GLAND", "GLAXO", "GLENMARK", "MEDANTA", "GODIGIT", "GPIL", "GODFRYPHLP", "GODREJAGRO", "GODREJCP", "GODREJIND", "GODREJPROP", "GRANULES", "GRAPHITE", "GRASIM", "GRAVITA", "GESHIP", "FLUOROCHEM", "GUJGASLTD", "GMDCLTD", "GSPL", "HEG", "HBLENGINE", "HCLTECH", "HDFCAMC", "HDFCBANK", "HDFCLIFE", "HFCL", "HAPPSTMNDS", "HAVELLS", "HEROMOTOCO", "HEXT", "HSCL", "HINDALCO", "HAL", "HINDCOPPER", "HINDPETRO", "HINDUNILVR", "HINDZINC", "POWERINDIA", "HOMEFIRST", "HONASA", "HONAUT", "HUDCO", "HYUNDAI", "ICICIBANK", "ICICIGI", "ICICIPRULI", "IDBI", "IDFCFIRSTB", "IFCI", "IIFL", "INOXINDIA", "IRB", "IRCON", "ITCHOTELS", "ITC", "ITI", "INDGN", "INDIACEM", "INDIAMART", "INDIANB", "IEX", "INDHOTEL", "IOC", "IOB", "IRCTC", "IRFC", "IREDA", "IGL", "INDUSTOWER", "INDUSINDBK", "NAUKRI", "INFY", "INOXWIND", "INTELLECT", "INDIGO", "IGIL", "IKS", "IPCALAB", "JBCHEPHARM", "JKCEMENT", "JBMA", "JKTYRE", "JMFINANCIL", "JSWENERGY", "JSWINFRA", "JSWSTEEL", "JPPOWER", "J&KBANK", "JINDALSAW", "JSL", "JINDALSTEL", "JIOFIN", "JUBLFOOD", "JUBLINGREA", "JUBLPHARMA", "JWL", "JYOTHYLAB", "JYOTICNC", "KPRMILL", "KEI", "KPITTECH", "KSB", "KAJARIACER", "KPIL", "KALYANKJIL", "KARURVYSYA", "KAYNES", "KEC", "KFINTECH", "KIRLOSBROS", "KIRLOSENG", "KOTAKBANK", "KIMS", "LTF", "LTTS", "LICHSGFIN", "LTFOODS", "LTIM", "LT", "LATENTVIEW", "LAURUSLABS", "LEMONTREE", "LICI", "LINDEINDIA", "LLOYDSME", "LODHA", "LUPIN", "MMTC", "MRF", "MGL", "MAHSCOOTER", "MAHSEAMLES", "M&MFIN", "M&M", "MANAPPURAM", "MRPL", "MANKIND", "MARICO", "MARUTI", "MFSL", "MAXHEALTH", "MAZDOCK", "METROPOLIS", "MINDACORP", "MSUMI", "MOTILALOFS", "MPHASIS", "MCX", "MUTHOOTFIN", "NATCOPHARM", "NBCC", "NCC", "NHPC", "NLCINDIA", "NMDC", "NSLNISP", "NTPCGREEN", "NTPC", "NH", "NATIONALUM", "NAVA", "NAVINFLUOR", "NESTLEIND", "NETWEB", "NEULANDLAB", "NEWGEN", "NAM-INDIA", "NIVABUPA", "NUVAMA", "NUVOCO", "OBEROIRLTY", "ONGC", "OIL", "OLAELEC", "OLECTRA", "PAYTM", "ONESOURCE", "OFSS", "POLICYBZR", "PCBL", "PGEL", "PIIND", "PNBHOUSING", "PTCIL", "PVRINOX", "PAGEIND", "PATANJALI", "PERSISTENT", "PETRONET", "PFIZER", "PHOENIXLTD", "PIDILITIND", "PPLPHARMA", "POLYMED", "POLYCAB", "POONAWALLA", "PFC", "POWERGRID", "PRAJIND", "PREMIERENE", "PRESTIGE", "PGHH", "PNB", "RRKABEL", "RBLBANK", "RECLTD", "RHIM", "RITES", "RADICO", "RVNL", "RAILTEL", "RAINBOW", "RKFORGE", "RCF", "REDINGTON", "RELIANCE", "RELINFRA", "RPOWER", "SBFC", "SBICARD", "SBILIFE", "SJVN", "SKFINDIA", "SRF", "SAGILITY", "SAILIFE", "SAMMAANCAP", "MOTHERSON", "SAPPHIRE", "SARDAEN", "SAREGAMA", "SCHAEFFLER", "THELEELA", "SCHNEIDER", "SCI", "SHREECEM", "SHRIRAMFIN", "SHYAMMETL", "ENRIN", "SIEMENS", "SIGNATURE", "SOBHA", "SOLARINDS", "SONACOMS", "SONATSOFTW", "STARHEALTH", "SBIN", "SAIL", "SUMICHEM", "SUNPHARMA", "SUNTV", "SUNDARMFIN", "SUNDRMFAST", "SUPREMEIND", "SUZLON", "SWANCORP", "SWIGGY", "SYNGENE", "SYRMA", "TBOTEK", "TVSMOTOR", "TATACHEM", "TATACOMM", "TCS", "TATACONSUM", "TATAELXSI", "TATAINVEST", "TATAMOTORS", "TATAPOWER", "TATASTEEL", "TATATECH", "TTML", "TECHM", "TECHNOE", "TEJASNET", "NIACL", "RAMCOCEM", "THERMAX", "TIMKEN", "TITAGARH", "TITAN", "TORNTPHARM", "TORNTPOWER", "TARIL", "TRENT", "TRIDENT", "TRIVENI", "TRITURBINE", "TIINDIA", "UCOBANK", "UNOMINDA", "UPL", "UTIAMC", "ULTRACEMCO", "UNIONBANK", "UBL", "UNITDSPR", "USHAMART", "VGUARD", "DBREALTY", "VTL", "VBL", "MANYAVAR", "VEDL", "VENTIVE", "VIJAYA", "VMM", "IDEA", "VOLTAS", "WAAREEENER", "WELCORP", "WELSPUNLIV", "WHIRLPOOL", "WIPRO", "WOCKPHARMA", "YESBANK", "ZFCVINDIA", "ZEEL", "ZENTEC", "ZENSARTECH", "ZYDUSLIFE", "ECLERX"]

        # -------------------------------------------------
        # 2. MAIN FORM – two columns
        # -------------------------------------------------
        col1, col2 = st.columns(2)

        with col1:
            dropdown_choice = st.selectbox(
                "Select Stock Symbol (NSE)",
                options=stock_list,
                index=0,
                key="add_trade_page_selector"
            )
            entry = st.number_input(
                "Entry",
                min_value=0.0,
                step=0.05,
                format="%.2f",
                key="add_trade_entry"
            )
            stop = st.number_input(
                "Stop Loss",
                min_value=0.0,
                step=0.05,
                format="%.2f",
                key="add_trade_stop"
            )
            target = st.number_input(
                "Target",
                min_value=0.0,
                step=0.05,
                format="%.2f",
                key="add_trade_target"
            )

        with col2:
            if dropdown_choice == "Enter Manually":
                manual_symbol = st.text_input(
                    "Enter Stock Symbol",
                    placeholder="e.g. NIFTY",
                    key="add_trade_manual_input"
                ).strip().upper()
                symbol_input = manual_symbol or "NIFTY"
            else:
                symbol_input = dropdown_choice

            direction = st.selectbox(
                "Direction",
                ["LONG", "SHORT"],
                key="add_trade_direction"
            )
            lot_size = st.number_input(
                "Lot Size (optional)",
                min_value=1,
                value=None,
                step=1,
                key="add_trade_lot"
            )
            note = st.text_area(
                "Note",
                height=80,
                key="add_trade_note"
            )

        # -------------------------------------------------
        # 3. SUBMIT
        # -------------------------------------------------
        if st.button("Add Trade", type="primary", key="add_trade_submit"):
            success, msg = atm.add_trade(
                symbol=symbol_input,
                entry=entry,
                stop=stop,
                target=target,
                lot_size=lot_size,
                note=note,
                # direction=direction
            )
            (st.success if success else st.error)(msg)
            st.rerun()


    # -------------------------------
    # Close Trade
    # -------------------------------
    elif menu == "Close Trade":
        st.header("Close Open Trade")
        if open_df.empty:
            st.info("No open trades to close.")
        else:
            st.dataframe(open_df, use_container_width=True)
            trade_id = st.selectbox("Select trade id to close", open_df["id"])
            exit_price = st.number_input("Exit Price", format="%.2f", value=0.0)
            note = st.text_area("Close Note")
            if st.button("Close Trade"):
                if exit_price <= 0:
                    st.error("Exit price must be > 0")
                else:
                    success, msg = atm.close_trade(trade_id, exit_price)
                    st.success(msg) if success else st.error(msg)
                    st.rerun()

    # -------------------------------
    # Import / Export
    # -------------------------------
    elif menu == "Import/Export":
        col1, col2 = st.columns(2)
        with col1:
            st.subheader("Export")
            table = st.selectbox("Table", ["open_trades", "trade_log", "daily_stats"])
            if st.button("Export CSV"):
                with atm.get_conn() as conn:
                    df = pd.read_sql(f"SELECT * FROM {table}", conn)
                csv = df.to_csv(index=False).encode()
                st.download_button("Download", csv, f"{table}.csv", "text/csv")
        with col2:
            st.subheader("Import")
            uploaded = st.file_uploader("CSV", type="csv")
            if uploaded and st.button("Import"):
                df = pd.read_csv(uploaded)
                req = ["symbol","entry","stop","target"]
                if all(c in df.columns for c in req):
                    with atm.get_conn() as conn:
                        cur = conn.cursor()
                        for _, r in df.iterrows():
                            cur.execute("""INSERT INTO open_trades
                                (symbol, entry, stop, target, lot_size, direction, note)
                                VALUES (?,?,?,?,?,?,?)""",
                                (r["symbol"], r["entry"], r["stop"], r["target"],
                                 r.get("lot_size"), r.get("direction","LONG"), r.get("note","")))
                        conn.commit()
                    st.success("Imported")
                    st.rerun()
                else:
                    st.error(f"Need: {req}")

    # -------------------------------
    # Reports
    # -------------------------------
    elif menu == "Reports":
        st.header("Reports")
        with atm.get_conn() as conn:
            df = pd.read_sql("SELECT * FROM trade_log", conn)
        if df.empty:
            st.info("No trade history.")
        else:
            df["date"] = pd.to_datetime(df["closed_at"]).dt.date
            grouped = df.groupby("date")["pnl"].sum().reset_index()
            max_abs = grouped["pnl"].abs().max()
            st.subheader("Daily PnL (ASCII)")
            for _, r in grouped.iterrows():
                bar = atm.ascii_bar(r.pnl, max_abs)
                color = "green" if r.pnl > 0 else "red"
                st.markdown(f"**{r.date}** | <span style='color:{color}'>₹{r.pnl:,.2f}</span> | {bar}", unsafe_allow_html=True)

    # -------------------------------
    # SQL Console
    # -------------------------------
    elif menu == "SQL Console":
        st.header("SQL Console")
        st.info("Only SELECT by default. Enable write for danger.")
        query = st.text_area("SQL Query", height=150, value="SELECT name FROM sqlite_master WHERE type='table';")
        allow_write = st.checkbox("Allow write statements", value=False)
        if st.button("Run SQL"):
            try:
                with atm.get_conn() as conn:
                    cur = conn.cursor()
                    q = query.strip()
                    if not allow_write and not q.lower().startswith("select"):
                        st.error("Only SELECT allowed.")
                    else:
                        cur.execute(q)
                        if q.lower().startswith("select"):
                            df = pd.read_sql_query(q, conn)
                            st.dataframe(df)
                        else:
                            conn.commit()
                            st.success("OK")
            except Exception as e:
                st.exception(e)

    # -------------------------------
    # Settings (FULLY WORKING)
    # -------------------------------
    elif menu == "Settings":
        st.subheader("Settings")
        atm.load_stats()                     # <-- make sure latest values are loaded

        c1, c2 = st.columns(2)

        # ------------------- LEFT COLUMN -------------------
        with c1:
            # Carry-forward toggle
            st.caption("Carry-forward")
            cf_status = "ON" if atm.carry_forward else "OFF"
            st.write(f"**{cf_status}**")
            if st.button("Toggle", key="toggle_carry_forward"):
                new_cf = 0 if atm.carry_forward else 1
                atm.update_stats({"carry_forward": new_cf})
                st.success("Carry-forward toggled")
                st.rerun()

            # Risk %
            st.caption("Risk %")
            risk = st.number_input("", 0.1, 5.0, atm.risk_pct, 0.1, key="risk")
            if risk != atm.risk_pct and st.button("Set", key="set_risk"):
                atm.risk_pct = risk
                st.success("Updated")
                st.rerun()

            # Max Open Trades
            st.caption("Max Open")
            mo = st.number_input("", 1, 10, atm.max_open_trades, key="mo")
            if mo != atm.max_open_trades and st.button("Set", key="set_mo"):
                atm.max_open_trades = int(mo)
                st.success("Updated")
                st.rerun()

        # ------------------- RIGHT COLUMN -------------------
        with c2:
            st.caption("Drawdown %")
            dd = st.number_input("", 0.0, 10.0, atm.max_drawdown_pct, 0.5, key="dd")
            st.caption("Profit Cap %")
            pp = st.number_input("", 0.0, 20.0, atm.max_profit_pct, 0.5, key="pp")
            if (dd != atm.max_drawdown_pct or pp != atm.max_profit_pct) and st.button("Save Caps"):
                atm.update_stats({"max_drawdown_pct": dd, "max_profit_pct": pp})
                st.success("Saved")
                st.rerun()

            # Edit Capital
            st.caption("Edit Capital")
            new_capital = st.number_input(
                "",
                min_value=1000.0,
                value=float(atm.capital),
                step=1000.0,
                format="%.0f",
                key="input_new_capital"
            )

            col_chk, col_btn = st.columns([1, 2])
            with col_chk:
                confirm_cap = st.checkbox("Confirm", key="confirm_capital_change")
            with col_btn:
                set_cap_btn = st.button("Set Capital", key="set_capital_btn")

            if set_cap_btn and confirm_cap:
                atm.update_stats({
                    "initial_capital": new_capital,
                    "capital": new_capital
                })
                st.success(f"Capital updated to ₹{new_capital:,.0f}")
                st.rerun()

        # ------------------- DB RESET (BOTTOM) -------------------
        st.markdown("---")
        if st.checkbox("Reset DB (DANGER)", key="chk_reset_db"):
            pwd = st.text_input("Type **RESET** to confirm", type="password", key="pwd_reset")
            col1, col2 = st.columns([1, 3])
            with col2:
                if st.button("WIPE DATABASE", type="secondary", key="btn_wipe_db"):
                    if pwd == "RESET":
                        atm.reset_db()
                        st.success("Database wiped")
                        st.rerun()
                    else:
                        st.error("Incorrect password")


    st.markdown("---")
    st.caption("Built for professional risk-controlled trading • © Prasad | AutoTradeManager")

if __name__ == "__main__":
    main()