"""
Sprint 0 验证脚本 — DataManager 全链路。

用法:
    python cli/demo_data_manager.py
    python cli/demo_data_manager.py --ts_code 600519.SH
    python cli/demo_data_manager.py --ts_code 300316.SZ --start 20250101
"""

import sys, os, argparse
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from database.connection import test_connection
from database.models import create_all_tables
from data.data_manager import DataManager


def main():
    p = argparse.ArgumentParser(description="Sprint 0 — DataManager 验证")
    p.add_argument("--ts_code", default="000001.SZ", help="测试股票代码（默认: 000001.SZ）")
    p.add_argument("--start", default="20250101", help="起始日期 YYYYMMDD（默认: 20250101）")
    args = p.parse_args()

    print("=" * 60)
    print("Sprint 0 — DataManager 验证")
    print("=" * 60)

    print("\n[1/5] 测试数据库连接...")
    if not test_connection():
        print("请先执行 shared/script/autossh.sh 建立 SSH 隧道")
        return
    print("[OK] 数据库连接成功")

    print("\n[2/5] 创建数据表...")
    dm = DataManager(); dm.init_db()
    print("[OK] 表结构已就绪")

    print("\n[3/5] 获取股票列表...")
    stocks = dm.get_stock_list()
    print("[OK] 共 {} 只股票".format(len(stocks)))
    print(stocks.head(10))

    print("\n[4/5] 获取日线数据 ({} start={})...".format(args.ts_code, args.start))
    try:
        daily = dm.get_daily(args.ts_code, start=args.start)
        if not daily.empty:
            print("[OK] 获取到 {} 条日线".format(len(daily)))
            print("  日期范围: {} ~ {}".format(daily['trade_date'].min(), daily['trade_date'].max()))
            print(daily.tail(5))
        else:
            print("[WARN] 日线数据为空（AkShare+Tushare 均不可用）")
    except Exception as e:
        print("[WARN] 日线获取异常: {}".format(e))

    print("\n[5/5] 增量同步测试...")
    try:
        count = dm.sync_daily(args.ts_code)
        print("[OK] 增量同步结果: {} 条".format(count))
    except Exception as e:
        print("[WARN] 增量同步异常: {}".format(e))

    try:
        from reports.storage import save_report
        save_report("## 数据层验证 — {}\n\n- 股票列表: OK\n- 日线数据: OK\n- 增量同步: OK".format(args.ts_code),
                    "数据层验证", subject_type="stock", subject_code=args.ts_code)
        print("\n  报告已存入 DB")
    except Exception:
        pass

    print("\n" + "=" * 60)
    print("验证完成")
    print("=" * 60)


if __name__ == "__main__":
    main()
