"""
rotate_logs.py — rotate and archive old log files.
Safe to run any time. Atomic moves via os.replace.
"""
import os
import csv
import json
from datetime import datetime, timedelta
from pathlib import Path
from zoneinfo import ZoneInfo

ET = ZoneInfo("America/New_York")
LOGS_DIR = Path("logs")
ARCHIVE_DIR = LOGS_DIR / "archive"
TRADES_PATH = Path("trades.csv")


def rotate_logs():
    """Rotate logs and archive old files."""
    today_et = datetime.now(ET).date()
    count = 0

    # Create archive dir if missing
    ARCHIVE_DIR.mkdir(parents=True, exist_ok=True)

    # Rotate .log and .jsonl files
    if LOGS_DIR.exists():
        for log_file in LOGS_DIR.glob("*.log"):
            mtime_et = datetime.fromtimestamp(log_file.stat().st_mtime, tz=ET).date()
            if mtime_et < today_et:
                archive_subdir = ARCHIVE_DIR / mtime_et.isoformat()
                archive_subdir.mkdir(parents=True, exist_ok=True)
                target = archive_subdir / log_file.name
                try:
                    os.replace(log_file, target)
                    count += 1
                except:
                    pass

        for jsonl_file in LOGS_DIR.glob("*.jsonl"):
            mtime_et = datetime.fromtimestamp(jsonl_file.stat().st_mtime, tz=ET).date()
            if mtime_et < today_et:
                archive_subdir = ARCHIVE_DIR / mtime_et.isoformat()
                archive_subdir.mkdir(parents=True, exist_ok=True)
                target = archive_subdir / jsonl_file.name
                try:
                    os.replace(jsonl_file, target)
                    count += 1
                except:
                    pass

    # Rotate trades.csv — keep last 90 days
    if TRADES_PATH.exists():
        cutoff_date = (today_et - timedelta(days=90)).isoformat()
        try:
            rows = list(csv.DictReader(open(TRADES_PATH)))
            header = None
            if rows:
                header = rows[0].keys()
            recent = [r for r in rows if r.get("timestamp_iso", "")[:10] >= cutoff_date]
            old = [r for r in rows if r.get("timestamp_iso", "")[:10] < cutoff_date]

            if old:
                # Archive old rows
                archive_date = datetime.now(ET).date().isoformat().replace("-", "")
                archive_file = ARCHIVE_DIR / f"trades_{archive_date}.csv"
                with open(archive_file, "w", newline="") as f:
                    if header:
                        writer = csv.DictWriter(f, fieldnames=header)
                        writer.writeheader()
                        writer.writerows(old)
                count += 1

                # Rewrite trades.csv with recent only
                tmp = TRADES_PATH.with_suffix(".tmp")
                with open(tmp, "w", newline="") as f:
                    if header:
                        writer = csv.DictWriter(f, fieldnames=header)
                        writer.writeheader()
                        writer.writerows(recent)
                os.replace(tmp, TRADES_PATH)
        except:
            pass

    # Rotate safety-check-log.json if > 5 MB
    safety_log = LOGS_DIR / "safety-check-log.json"
    if safety_log.exists():
        size_mb = safety_log.stat().st_size / (1024 * 1024)
        if size_mb > 5:
            archive_date = datetime.now(ET).date().isoformat().replace("-", "")
            archive_file = ARCHIVE_DIR / f"safety-check-log_{archive_date}.json"
            try:
                os.replace(safety_log, archive_file)
                count += 1
            except:
                pass

    print(f"Rotated {count} files to logs/archive/")


if __name__ == "__main__":
    rotate_logs()
