# source: https://raw.githubusercontent.com/CETANGZHI/flowainew/94cc7095db1259c5f1cb053bdf5c74bb0c4c16c3/backend/scripts/init_prompt_examples.py
import sys
import os
from pathlib import Path

# Add backend directory to python path
backend_dir = Path(__file__).resolve().parent.parent
sys.path.append(str(backend_dir))

from app.database import SessionLocal, init_db
from app.models.database import PromptExample
from sqlalchemy import select

def init_data():
    print("Initializing database tables...")
    init_db()
    
    db = SessionLocal()
    try:
        # Check if examples already exist
        stmt = select(PromptExample).limit(1)
        existing = db.execute(stmt).scalar()
        
        if existing:
            print("Prompt examples already exist. Skipping insertion.")
            return

        print("Inserting sample prompt examples...")
        
        examples = [
            PromptExample(
                scenario='market_analysis',
                user_level='intermediate',
                user_query='BTC现在能买吗?',
                assistant_response="""基于当前市场状况,我从3个维度分析:

📊 **技术面**:
- 日线级别: BTC在$67,000-$68,000形成平台整理
- MACD金叉,RSI 53(中性偏多)
- 关键支撑: $65,500(前期密集成交区)
- 关键阻力: $69,500(历史高点)
- 结论: 短期震荡偏多,突破$69,500有望冲击$72,000

💰 **链上数据**:
- 交易所净流出2.3万枚(24h),抛压减轻
- 巨鲸地址持仓+1.2%,机构在建仓
- 活跃地址数+15%,市场参与度提升

⚠️ **风险提示**:
- 美联储会议在即,关注加息预期
- 建议分批建仓: 首批30%,突破$69,500再加30%
- 止损设在$65,000下方,风险报酬比1:3

**操作建议**: 当前可小仓位试探(总仓位10-20%),等待突破确认后加仓""",
                quality_score=0.95,
                human_reviewed=True,
                tags=['BTC', 'technical_analysis', 'risk_management']
            ),
            PromptExample(
                scenario='strategy_development',
                user_level='advanced',
                user_query='帮我写一个RSI超卖反弹策略',
                assistant_response="""好的，这是一个基于 RSI 超卖反弹的均值回归策略，适用于震荡行情。

# 策略逻辑
1. **入场**: RSI(14) < 30 (超卖) 且 收盘价 > MA(200) (长期趋势向上)
2. **出场**: RSI(14) > 70 (超买) 或 止损触发
3. **止损**: ATR(14) * 2

# 代码实现 (Freqtrade)
```python
class Github_CETANGZHI_flowainew__init_prompt_examples__20260114_114646(IStrategy):
    # 参数设置
    buy_rsi = IntParameter(20, 40, default=30, space="buy")
    sell_rsi = IntParameter(60, 80, default=70, space="sell")
    
    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14)
        dataframe['ma200'] = ta.SMA(dataframe, timeperiod=200)
        dataframe['atr'] = ta.ATR(dataframe, timeperiod=14)
        return dataframe

    def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        dataframe.loc[
            (
                (dataframe['rsi'] < self.buy_rsi.value) &
                (dataframe['close'] > dataframe['ma200'])
            ),
            'enter_long'] = 1
        return dataframe

    def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        dataframe.loc[
            (dataframe['rsi'] > self.sell_rsi.value),
            'exit_long'] = 1
        return dataframe
```

# 回测建议
- 推荐周期: 1h / 4h
- 适用币种: BTC, ETH (流动性好)
- 注意事项: 单边下跌行情中可能过早抄底，建议配合趋势过滤器。""",
                quality_score=0.90,
                human_reviewed=True,
                tags=['strategy', 'RSI', 'mean_reversion']
            )
        ]
        
        db.add_all(examples)
        db.commit()
        print(f"Successfully inserted {len(examples)} examples.")
        
    except Exception as e:
        print(f"Error: {e}")
        db.rollback()
    finally:
        db.close()

if __name__ == "__main__":
    init_data()
