#!/usr/bin/env python3
import sys
import json
import argparse
from datetime import datetime
import zoneinfo

import sys

if sys.stdout.encoding and sys.stdout.encoding.lower() not in ("utf-8", "utf8"):
    sys.stdout = open(sys.stdout.fileno(), mode="w", encoding="utf-8", buffering=1)


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--timezone", default="Asia/Seoul")
    parser.add_argument("--out", default="Temp/operating_cadence_signal_v1.json")
    args = parser.parse_args()

    # Detect current KST date
    tz = zoneinfo.ZoneInfo(args.timezone)
    now = datetime.now(tz)
    
    day_name = now.strftime("%A")
    date_day = now.day
    
    rebalance_required = day_name in ("Saturday", "Sunday")
    interim_check_required = date_day in (1, 11, 21)

    result = {
        "formula_id": "OPERATING_CADENCE_SIGNAL_V1",
        "timestamp": now.isoformat(),
        "day_of_week": day_name,
        "day_of_month": date_day,
        "rebalance_required": rebalance_required,
        "interim_check_required": interim_check_required
    }

    from pathlib import Path
    ROOT = Path(__file__).resolve().parents[1]
    out_path = ROOT / args.out
    out_path.parent.mkdir(parents=True, exist_ok=True)
    out_path.write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding="utf-8")
    
    print(f"Saved operating cadence signal to {out_path}")
    sys.exit(0)

if __name__ == "__main__":
    main()
