"""
V11 — Logger: CSV para momentum taker.

Más simple que V10: solo trades y windows (sin quotes ni fills separados).
"""
import csv, time
from pathlib import Path
from .config import Config, write_json


class Logger:
    def __init__(self, cfg: Config):
        self.cfg = cfg
        cfg.log_dir.mkdir(parents=True, exist_ok=True)
        self._init_csv_files()

    def _init_csv_files(self):
        c = self.cfg
        if not c.trades_csv.exists():
            with open(c.trades_csv, "w", newline="") as f:
                csv.writer(f).writerow([
                    "ts", "slug", "side", "price", "size", "cost",
                    "move_pct", "outcome", "pnl_gross", "fee", "pnl_net",
                ])
        if not c.windows_csv.exists():
            with open(c.windows_csv, "w", newline="") as f:
                csv.writer(f).writerow([
                    "ts", "slug", "start_ts", "end_ts",
                    "strike", "price_final", "outcome",
                    "side", "entry_price", "size",
                    "move_pct", "pnl_gross", "fee", "pnl_net",
                ])

    def log_trade(self, slug, side, price, size, cost,
                  move_pct, outcome, pnl_gross, fee, pnl_net):
        with open(self.cfg.trades_csv, "a", newline="") as f:
            csv.writer(f).writerow([
                int(time.time()), slug, side,
                round(price, 4), round(size, 2), round(cost, 4),
                round(move_pct, 4), outcome,
                round(pnl_gross, 4), round(fee, 4), round(pnl_net, 4),
            ])

    def log_window(self, m, price_final, outcome,
                   side, entry_price, size,
                   move_pct, pnl_gross, fee, pnl_net):
        with open(self.cfg.windows_csv, "a", newline="") as f:
            csv.writer(f).writerow([
                int(time.time()), m.slug, m.start_ts, m.end_ts,
                round(m.strike, 4) if m.strike else "",
                round(price_final, 4),
                outcome,
                side or "", round(entry_price, 4), round(size, 2),
                round(move_pct, 4),
                round(pnl_gross, 4), round(fee, 4), round(pnl_net, 4),
            ])

    def write_state(self, data: dict):
        write_json(self.cfg.state_json, data)
