#!/usr/bin/env python3
"""修正趋势保本移交后 monitor_type 仍为「下单监控」的历史数据."""
from __future__ import annotations

import argparse
import sqlite3
from pathlib import Path

from lib.strategy.strategy_trade_labels import MONITOR_TYPE_TREND_PULLBACK


def main() -> int:
    parser = argparse.ArgumentParser(description="Fix trend handoff order/trade monitor_type labels.")
    parser.add_argument("--db", required=True, help="Path to instance sqlite db")
    parser.add_argument("--dry-run", action="store_true", help="Preview only")
    parser.add_argument("--apply", action="store_true", help="Apply updates")
    args = parser.parse_args()
    if not args.dry_run and not args.apply:
        args.dry_run = True

    db_path = Path(args.db).expanduser().resolve()
    if not db_path.is_file():
        print(f"[ERR] DB not found: {db_path}")
        return 1

    conn = sqlite3.connect(str(db_path))
    conn.row_factory = sqlite3.Row
    cur = conn.cursor()

    cur.execute(
        """
        SELECT COUNT(*) AS c FROM order_monitors
        WHERE trend_plan_id IS NOT NULL AND trend_plan_id > 0
          AND (monitor_type IS NULL OR TRIM(monitor_type) = '' OR monitor_type = '下单监控')
        """
    )
    om_n = int(cur.fetchone()["c"])
    cur.execute(
        """
        SELECT COUNT(*) AS c FROM trade_records
        WHERE trend_plan_id IS NOT NULL AND trend_plan_id > 0
          AND (monitor_type IS NULL OR TRIM(monitor_type) = '' OR monitor_type = '下单监控')
        """
    )
    tr_n = int(cur.fetchone()["c"])
    print(f"[INFO] order_monitors to fix: {om_n}")
    print(f"[INFO] trade_records to fix: {tr_n}")

    if args.dry_run:
        conn.close()
        return 0

    cur.execute(
        """
        UPDATE order_monitors
        SET monitor_type=?
        WHERE trend_plan_id IS NOT NULL AND trend_plan_id > 0
          AND (monitor_type IS NULL OR TRIM(monitor_type) = '' OR monitor_type = '下单监控')
        """,
        (MONITOR_TYPE_TREND_PULLBACK,),
    )
    cur.execute(
        """
        UPDATE trade_records
        SET monitor_type=?
        WHERE trend_plan_id IS NOT NULL AND trend_plan_id > 0
          AND (monitor_type IS NULL OR TRIM(monitor_type) = '' OR monitor_type = '下单监控')
        """,
        (MONITOR_TYPE_TREND_PULLBACK,),
    )
    conn.commit()
    conn.close()
    print("[OK] Applied.")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
