"""
position_manager.py

Owns local position state for this project: sizing a new position off
smart_engine.py's own Stage 3 stop (no separate risk_manager here --
that stop is already computed at entry-decision time and reused
directly), submitting entry/exit orders through alpaca_client, and
persisting to data_store so a mid-day restart doesn't lose track of
what's actually open.

Deliberately leaner than screener/premarket's position_manager.py: no
momentum-fade exit logic (that's exit.py's job, called from
monitor.py), no entry-attempt tracker, no fade-confirmed exit. Reuses
the same wash-trade / position-not-found error handling already coded
into alpaca_client.py, since those are real broker-timing races
already proven to happen against this same paper-account family, not
something worth reinventing.

Known simplification: a filled position is recorded locally at the
smart_engine decision price (the market price at the instant BUY
fired), not the order's actual average fill price -- a market order
can fill a few cents away. Same simplification alpaca_client.py's own
docstrings note sip_bot's position_manager.py makes at entry time.
Acceptable for now; revisit if fill slippage turns out to matter once
there's real trade data.
"""

import math
from datetime import datetime, timezone

from config_loader import get_config
from logger_setup import get_logger
from alpaca_client import get_client, parse_wash_trade_error, parse_position_not_found_error
import data_store

log = get_logger("position_manager")


class PositionManager:
    def __init__(self):
        self.client = get_client()
        self.cfg = get_config()["trading"]
        self.positions = data_store.load_positions()

    # ------------------------------------------------------------------
    def open_positions_count(self) -> int:
        return len(self.positions)

    def has_available_slot(self) -> bool:
        return self.open_positions_count() < self.cfg["max_positions"]

    def is_symbol_open(self, symbol: str) -> bool:
        return symbol in self.positions

    def get_open_symbols(self) -> list:
        return list(self.positions.keys())

    # ------------------------------------------------------------------
    def calculate_qty(self, equity: float, entry_price: float, stop_price: float) -> int:
        """Risk account_risk_pct_per_trade% of equity on the distance
        between entry and the supplied stop, capped so no single
        position exceeds max_position_notional_pct_of_equity."""
        risk_per_share = entry_price - stop_price
        if risk_per_share <= 0 or not entry_price:
            return 0

        risk_dollars = equity * self.cfg["account_risk_pct_per_trade"] / 100.0
        qty = math.floor(risk_dollars / risk_per_share)

        notional_cap = equity * self.cfg["max_position_notional_pct_of_equity"] / 100.0
        qty = min(qty, math.floor(notional_cap / entry_price))

        return qty if qty >= self.cfg["min_shares"] else 0

    # ------------------------------------------------------------------
    def enter_position(self, symbol: str, entry_price: float, stop_price: float,
                        reasons: list = None, quote: tuple = None) -> bool:
        if self.is_symbol_open(symbol) or not self.has_available_slot():
            return False

        account = self.client.get_account()
        equity = float(account.equity)
        qty = self.calculate_qty(equity, entry_price, stop_price)
        if qty <= 0:
            log.info(f"[ENTRY] {symbol} sized to 0 shares (equity=${equity:.2f}, "
                     f"entry=${entry_price:.2f}, stop=${stop_price:.2f}) -- skipped")
            return False

        eo = self.cfg.get("entry_order") or {}
        if eo.get("type") in ("limit_mid", "limit_ask") and quote and quote[0] and quote[1] and quote[1] >= quote[0] > 0:
            # [2026-10-07] LIMIT entry at the quote midpoint; the position is PENDING until filled, cancelled after
            # wait_seconds if not (check_pending_entries, every poll)
            # [2026-10-08, user] "limit_ask": limit at the ASK (marketable, capped) -- mid limits never filled on paper
            mid = quote[1] if eo.get("type") == "limit_ask" else (quote[0] + quote[1]) / 2
            try:
                order = self.client.submit_limit_order(symbol, qty, "buy", mid)
            except Exception as e:
                log.error(f"[ENTRY] {symbol} limit order failed: {e}")
                return False
            now = datetime.now(timezone.utc)
            self.positions[symbol] = {
                "symbol": symbol, "qty": qty, "entry_price": round(mid, 4), "stop_price": stop_price,
                "entry_time": now.isoformat(), "entry_order_id": str(getattr(order, "id", "")),
                "reasons": reasons or [], "pending": True, "limit_price": round(mid, 4),
                "signal_price": entry_price, "submitted_at": now.isoformat(),
            }
            self._save()
            log.info(f"[ENTRY] {symbol} LIMIT BUY {qty} @ ${mid:.2f} ({'ask' if eo.get('type') == 'limit_ask' else 'mid'} of {quote[0]:.2f}/{quote[1]:.2f}; signal "
                     f"${entry_price:.2f}; wait {eo.get('wait_seconds', 30)}s; stop ${stop_price:.2f})")
            return True

        try:
            order = self.client.submit_market_order(symbol, qty, "buy")
        except Exception as e:
            log.error(f"[ENTRY] {symbol} order submission failed: {e}")
            return False

        now = datetime.now(timezone.utc)
        self.positions[symbol] = {
            "symbol": symbol, "qty": qty, "entry_price": entry_price,
            "stop_price": stop_price, "entry_time": now.isoformat(),
            "entry_order_id": str(getattr(order, "id", "")),
            "reasons": reasons or [],
        }
        self._save()
        log.info(f"[ENTRY] {symbol} BUY {qty} @ ~${entry_price:.2f} "
                 f"(stop ${stop_price:.2f}, reasons: {'; '.join(reasons or [])})")
        return True

    # ------------------------------------------------------------------
    def check_pending_exits(self):
        """[2026-10-07] limit sells: filled -> trade recorded at the fill; not filled after wait_seconds -> cancel, the rest
        at market."""
        wait = (self.cfg.get("exit_order") or {}).get("wait_seconds", 20)
        for symbol in [s for s, p in self.positions.items() if p.get("exiting")]:
            p = self.positions[symbol]; x = p["exiting"]
            o = self.client.get_order(x["order_id"])
            if o is None:
                continue
            status = str(o.status).split(".")[-1].lower()
            age = (datetime.now(timezone.utc) - datetime.fromisoformat(x["submitted_at"])).total_seconds()
            if status == "filled":
                self._finish_limit_exit(symbol, o, x["reason"])
            elif age >= wait or status in ("canceled", "cancelled", "expired", "rejected"):
                self.client.cancel_order_id(x["order_id"])
                o = self.client.get_order(x["order_id"]) or o
                if str(o.status).split(".")[-1].lower() == "filled":
                    self._finish_limit_exit(symbol, o, x["reason"]); continue
                x["filled"] = float(o.filled_qty or 0)
                x["fill_px"] = float(o.filled_avg_price) if o.filled_avg_price else None
                log.info(f"[EXIT] {symbol} limit sell @ ${x['limit']:.2f} not (fully) filled in {int(age)}s "
                         f"({int(x['filled'])} of {p['qty']}) -- rest at market")
                self.exit_position(symbol, x["signal_price"], x["reason"] + " (limit not filled -> market)")

    def _finish_limit_exit(self, symbol, o, reason):
        p = self.positions[symbol]
        px = float(o.filled_avg_price)
        pl_pct = (px - p["entry_price"]) / p["entry_price"] * 100.0 if p["entry_price"] else 0.0
        trade = {**{k: v for k, v in p.items() if k != "exiting"}, "exit_price": px,
                 "exit_time": datetime.now(timezone.utc).isoformat(), "exit_order_id": str(o.id),
                 "exit_reason": reason + " [limit sell]", "status": "closed",
                 "pl_pct": round(pl_pct, 3), "pl_dollars": round((px - p["entry_price"]) * p["qty"], 2)}
        data_store.append_trade_record(trade)
        del self.positions[symbol]
        self._save()
        log.info(f"[EXIT] {symbol} SELL {p['qty']} @ ${px:.2f} -- limit filled ({reason}) -- P/L {pl_pct:+.2f}% (${trade['pl_dollars']:+.2f})")

    def check_pending_entries(self):
        """[2026-10-07] limit entries: filled -> becomes a normal position at the real fill; not filled within
        wait_seconds -> cancel (a partial fill is kept at its filled quantity)."""
        wait = (self.cfg.get("entry_order") or {}).get("wait_seconds", 30)
        for symbol in [s for s, p in self.positions.items() if p.get("pending")]:
            p = self.positions[symbol]
            o = self.client.get_order(p["entry_order_id"])
            if o is None:
                continue
            filled = float(o.filled_qty or 0)
            status = str(o.status).split(".")[-1].lower()
            age = (datetime.now(timezone.utc) - datetime.fromisoformat(p["submitted_at"])).total_seconds()
            if status == "filled":
                self._activate(symbol, o, filled, "filled")
            elif age >= wait or status in ("canceled", "cancelled", "expired", "rejected"):
                if status not in ("canceled", "cancelled", "expired", "rejected"):
                    self.client.cancel_order_id(p["entry_order_id"])
                    o = self.client.get_order(p["entry_order_id"]) or o      # a fill can land during the cancel
                    filled = float(o.filled_qty or 0)
                if filled >= 1:
                    self._activate(symbol, o, filled, f"partly filled ({int(filled)} of {p['qty']}), rest cancelled")
                else:
                    log.info(f"[ENTRY] {symbol} limit @ ${p['limit_price']:.2f} NOT filled in {int(age)}s -- cancelled, no trade")
                    del self.positions[symbol]
                    self._save()

    def _activate(self, symbol, o, filled, how):
        p = self.positions[symbol]
        p["qty"] = int(filled)
        if o.filled_avg_price:
            p["entry_price"] = float(o.filled_avg_price)
        if getattr(o, "filled_at", None):
            p["entry_time"] = o.filled_at.isoformat()
        p.pop("pending", None)
        self._save()
        log.info(f"[ENTRY] {symbol} BUY {p['qty']} @ ${p['entry_price']:.2f} -- limit {how} (signal ${p.get('signal_price', 0):.2f}, "
                 f"stop ${p['stop_price']:.2f}, reasons: {'; '.join(p.get('reasons') or [])})")

    def exit_position(self, symbol: str, exit_price: float, reason: str, limit_quote: tuple = None):
        p = self.positions.get(symbol)
        if not p:
            return
        xo = self.cfg.get("exit_order") or {}
        if p.get("exiting"):
            if limit_quote is not None:
                return                                    # a limit sell is already working
            # [2026-10-07] a RISK exit (safety stop / EOD) while a limit sell works: cancel it, sell the rest at market
            self.client.cancel_order_id(p["exiting"]["order_id"])
            o = self.client.get_order(p["exiting"]["order_id"])
            p["exiting"]["filled"] = float(getattr(o, "filled_qty", 0) or 0) if o else 0.0
            p["exiting"]["fill_px"] = float(o.filled_avg_price) if o is not None and o.filled_avg_price else None
            if p["exiting"]["filled"] >= p["qty"]:
                return self._finish_limit_exit(symbol, o, p["exiting"]["reason"])
        elif (limit_quote is not None and xo.get("type") == "limit_mid" and not p.get("pending")
              and limit_quote[0] and limit_quote[1] and limit_quote[1] >= limit_quote[0] > 0):
            # [2026-10-07] the user: non-risk exits as a LIMIT SELL at the midpoint; market after wait_seconds
            mid = (limit_quote[0] + limit_quote[1]) / 2
            try:
                o = self.client.submit_limit_order(symbol, int(p["qty"]), "sell", mid)
                p["exiting"] = {"order_id": str(o.id), "limit": round(mid, 4), "reason": reason, "signal_price": exit_price,
                                "submitted_at": datetime.now(timezone.utc).isoformat()}
                self._save()
                log.info(f"[EXIT] {symbol} LIMIT SELL {p['qty']} @ ${mid:.2f} (mid of {limit_quote[0]:.2f}/{limit_quote[1]:.2f}; "
                         f"market after {xo.get('wait_seconds', 20)}s) -- {reason}")
                return
            except Exception as e:
                log.warning(f"[EXIT] {symbol} limit sell failed ({e}) -- selling at market")
        if p.get("pending"):
            # never sell an unfilled limit entry -- cancel it instead (EOD / shutdown)
            self.client.cancel_order_id(p["entry_order_id"])
            o = self.client.get_order(p["entry_order_id"])
            if o is not None and float(o.filled_qty or 0) >= 1:
                self._activate(symbol, o, float(o.filled_qty), "filled at cancel")
                p = self.positions[symbol]
            else:
                log.info(f"[EXIT] {symbol}: pending limit entry cancelled ({reason})")
                del self.positions[symbol]
                self._save()
                return

        exit_order_id = None
        try:
            o = self.client.close_position(symbol)
            exit_order_id = str(getattr(o, "id", "") or "") or None   # [2026-10-07] for the real fill (reconcile_fills.py)
        except Exception as e:
            order_id = parse_wash_trade_error(e)
            if order_id:
                # [BUGFIX 2026-09-22] Used to assume the resting order was
                # a close and drop the position. On 2026-09-21 it was
                # UUUU's own still-unfilled entry BUY: the bot logged a
                # fake exit, the BUY then filled, and 164 shares sat
                # untracked overnight tying up ~$2k of buying power.
                if not self._resolve_wash_conflict(symbol, order_id):
                    return
            elif parse_position_not_found_error(e):
                if not self._entry_never_filled(symbol, p):
                    log.warning(f"[EXIT] {symbol} broker reports no position yet "
                                f"(entry order likely still settling) -- will retry next poll")
                return
            else:
                log.error(f"[EXIT] {symbol} close_position failed: {e}")
                return

        if p.get("cancelled_entry_order_id"):
            # Entry was cancelled mid-fill; P/L on what actually filled.
            order = self.client.get_order(p["cancelled_entry_order_id"])
            if order is not None and float(order.filled_qty or 0) > 0:
                p["qty"] = int(float(order.filled_qty))

        ex = p.pop("exiting", None)
        if ex and ex.get("filled") and ex.get("fill_px"):
            f = min(ex["filled"], p["qty"])
            exit_price = (ex["fill_px"] * f + exit_price * (p["qty"] - f)) / p["qty"]
            exit_order_id = ",".join(x for x in (ex["order_id"], exit_order_id) if x)
        pl_pct = (exit_price - p["entry_price"]) / p["entry_price"] * 100.0 if p["entry_price"] else 0.0
        pl_dollars = (exit_price - p["entry_price"]) * p["qty"]
        trade = {
            **p, "exit_price": exit_price, "exit_time": datetime.now(timezone.utc).isoformat(), "exit_order_id": exit_order_id,
            "exit_reason": reason, "status": "closed",
            "pl_pct": round(pl_pct, 3), "pl_dollars": round(pl_dollars, 2),
        }
        data_store.append_trade_record(trade)
        del self.positions[symbol]
        self._save()
        log.info(f"[EXIT] {symbol} SELL @ ~${exit_price:.2f} ({reason}) -- "
                 f"P/L {pl_pct:+.2f}% (${pl_dollars:+.2f})")

    # ------------------------------------------------------------------
    def _resolve_wash_conflict(self, symbol: str, order_id: str) -> bool:
        """close_position() was rejected because order_id is resting on
        the other side. True = the position is genuinely being closed
        (record the exit now); False = keep it tracked, retry next poll."""
        p = self.positions[symbol]
        order = self.client.get_order(order_id)
        if order is None:
            log.warning(f"[EXIT] {symbol} wash-trade conflict with {order_id} but couldn't "
                        f"fetch that order -- keeping position, will retry next poll")
            return False

        side = getattr(order.side, "value", str(order.side)).lower()
        status = getattr(order.status, "value", str(order.status)).lower()
        if side == "sell":
            log.warning(f"[EXIT] {symbol} a SELL ({order_id}, {status}) is already working; "
                        f"treating as being closed out")
            return True

        # The conflict is a BUY -- normally our own entry that hasn't
        # filled yet. Cancel it so the next poll's close goes through
        # (or finds nothing to close if it never filled at all).
        log.warning(f"[EXIT] {symbol} close blocked by our resting BUY {order_id} ({status}); "
                    f"cancelling it and keeping the position tracked")
        self.client.cancel_order(order_id)
        p["cancelled_entry_order_id"] = order_id
        self._save()
        return False

    def _entry_never_filled(self, symbol: str, p: dict) -> bool:
        """Broker says no position. If the entry order is dead with zero
        fill and the broker really holds nothing, stop tracking it (there
        was no trade); otherwise the entry is still settling."""
        order_id = p.get("cancelled_entry_order_id") or p.get("entry_order_id")
        order = self.client.get_order(order_id) if order_id else None
        if order is None:
            return False
        status = getattr(order.status, "value", str(order.status)).lower()
        filled = float(order.filled_qty or 0)
        if status not in ("canceled", "expired", "rejected") or filled > 0:
            return False
        if self.client.get_position_qty(symbol) != 0:
            return False
        log.warning(f"[EXIT] {symbol} entry order {order_id} {status} with no fill -- "
                    f"no trade happened, dropping position")
        del self.positions[symbol]
        self._save()
        return True

    def _save(self):
        data_store.save_positions(self.positions)
