"""Offline accounting exercise; synthetic bars and fixed signals, no broker/API.

Python 3.11+; standard library only. Money is Decimal, stored as TEXT.
Not a live simulator: no tax, minimum fee, limits, halts, dividends or liquidity.
"""
import argparse
import hashlib
import json
import sqlite3
from datetime import date as iso_date
from decimal import Decimal as D

COMMISSION = D("0.0003")  # 3 per 10,000 on both sides; deliberately excludes tax
SLIPPAGE = D("0.001")    # buys above / sells below the next supplied bar's open
INITIAL_CASH = D("100000")
BARS = [("2025-01-06", "10", "10"), ("2025-01-07", "10", "10.5"),
        ("2025-01-08", "10.8", "11"), ("2025-01-09", "11", "10.9"),
        ("2025-01-10", "10.7", "10.8")]
SIGNALS = {"2025-01-06": "BUY", "2025-01-08": "SELL", "2025-01-10": "BUY"}


def run(db_path, bars=BARS, signals=None):
    signals = SIGNALS if signals is None else signals
    dates = [b[0] for b in bars]
    if not bars or dates != sorted(set(dates)):
        raise ValueError("Bars must have unique ascending ISO dates")
    for date in dates:
        if iso_date.fromisoformat(date).isoformat() != date:
            raise ValueError("Use YYYY-MM-DD dates")
    if not set(signals) <= set(dates) or any(s not in ("BUY", "SELL") for s in signals.values()):
        raise ValueError("Each signal must be BUY/SELL on a supplied bar")
    if any(not D(o).is_finite() or not D(c).is_finite() or D(o) <= 0 or D(c) <= 0 for _, o, c in bars):
        raise ValueError("Prices must be finite and positive")
    payload = json.dumps([bars, signals, str(INITIAL_CASH), str(COMMISSION), str(SLIPPAGE), "v1"], sort_keys=True)
    run_id = hashlib.sha256(payload.encode()).hexdigest()
    db = sqlite3.connect(db_path)
    try:
        with db:
            db.executescript("""
CREATE TABLE IF NOT EXISTS runs(run_id TEXT PRIMARY KEY, inputs TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS signals(run_id TEXT, date TEXT, side TEXT, status TEXT,
  PRIMARY KEY(run_id,date));
CREATE TABLE IF NOT EXISTS fills(run_id TEXT, signal_date TEXT, date TEXT, side TEXT,
  price TEXT, shares INTEGER, fee TEXT, PRIMARY KEY(run_id,signal_date));
CREATE TABLE IF NOT EXISTS equity(run_id TEXT, date TEXT, cash TEXT, shares INTEGER,
  close TEXT, value TEXT, PRIMARY KEY(run_id,date));
""")
            exists = db.execute("SELECT 1 FROM runs WHERE run_id=?", (run_id,)).fetchone()
            if not exists:
                db.execute("INSERT INTO runs VALUES (?,?)", (run_id, payload))
                cash, shares, pending = INITIAL_CASH, 0, None
                for date, open_, close in bars:
                    if pending:
                        signal_date, side = pending
                        qty = 100 if side == "BUY" else shares
                        price = D(open_) * (1 + SLIPPAGE if side == "BUY" else 1 - SLIPPAGE)
                        fee = price * qty * COMMISSION
                        accepted = (side == "BUY" and shares == 0 and cash >= price * qty + fee) or (side == "SELL" and qty > 0)
                        if accepted:
                            cash += (-price * qty - fee) if side == "BUY" else (price * qty - fee)
                            shares += qty if side == "BUY" else -qty
                            db.execute("INSERT INTO fills VALUES (?,?,?,?,?,?,?)", (run_id, signal_date, date, side, str(price), qty, str(fee)))
                        db.execute("UPDATE signals SET status=? WHERE run_id=? AND date=?", ("filled" if accepted else "rejected", run_id, signal_date))
                        pending = None
                    if date in signals:  # only after this bar's close is known
                        side = signals[date]
                        db.execute("INSERT INTO signals VALUES (?,?,?,?)", (run_id, date, side, "pending"))
                        pending = (date, side)
                    value = cash + shares * D(close)
                    db.execute("INSERT INTO equity VALUES (?,?,?,?,?,?)", (run_id, date, str(cash), shares, close, str(value)))
        cash, shares, value = db.execute("SELECT cash,shares,value FROM equity WHERE run_id=? ORDER BY date DESC LIMIT 1", (run_id,)).fetchone()
        count = lambda table: db.execute(f"SELECT COUNT(*) FROM {table} WHERE run_id=?", (run_id,)).fetchone()[0]
        pending_count = db.execute("SELECT COUNT(*) FROM signals WHERE run_id=? AND status='pending'", (run_id,)).fetchone()[0]
        return {"signals": count("signals"), "fills": count("fills"), "equity_rows": count("equity"), "pending": pending_count,
                "cash": f"{D(cash):.2f}", "shares": shares, "value": f"{D(value):.2f}"}
    finally:
        db.close()


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--db", default="paper-demo.db", help="Use a dedicated demo database, not a production file")
    args = parser.parse_args()
    print(json.dumps(run(args.db), sort_keys=True))
