from sqlalchemy import create_engine, Column, Integer, String, Text, DateTime, JSON
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, Session
from datetime import datetime
import os
import logging
from typing import Optional, List, Dict

# 设置日志记录
logger = logging.getLogger(__name__)

# 获取项目根目录的绝对路径
ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# 数据库配置
DB_CONFIG = {
    'host': '192.168.18.199',
    'port': 3306,
    'user': 'root',
    'password': 'Chlry#$.8',
    'database': 'db_gp_cj'
}

# 创建数据库连接URL
DATABASE_URL = f"mysql+pymysql://{DB_CONFIG['user']}:{DB_CONFIG['password']}@{DB_CONFIG['host']}:{DB_CONFIG['port']}/{DB_CONFIG['database']}"

# 创建数据库引擎
engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()


class GpFundamentalAnalysis(Base):
    """基本面分析结果表"""
    __tablename__ = "fundamental_analysis"

    id = Column(Integer, primary_key=True, index=True)
    stock_code = Column(String(10), nullable=False, comment="股票代码")
    stock_name = Column(String(50), nullable=False, comment="股票名称")
    dimension = Column(String(50), nullable=False, comment="分析维度")
    ai_response = Column(Text, nullable=False, comment="AI分析结果")
    reasoning_process = Column(Text, comment="推理过程")
    references = Column(JSON, comment="参考资料")
    update_time = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment="更新时间")
    extra_info = Column(JSON, comment="扩展信息")

    def __repr__(self):
        return f"<GpFundamentalAnalysis(stock_code={self.stock_code}, dimension={self.dimension})>"


def init_db():
    """初始化数据库"""
    Base.metadata.create_all(bind=engine)


def get_db():
    """获取数据库会话"""
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


# 定义基本面分析的维度
ANALYSIS_DIMENSIONS = {
    "company_profile": "公司简介",
    "business_background": "业务背景",
    "core_advantages": "核心优势",
    "management_team": "管理团队",
    "financial_performance": "财务表现",
    "risk_factors": "风险因素",
    "development_prospects": "发展前景",
    "investment_suggestion": "投资建议"
}


def save_analysis_result(
        db: Session,
        stock_code: str,
        stock_name: str,
        dimension: str,
        ai_response: str,
        reasoning_process: Optional[str] = None,
        references: Optional[List[Dict]] = None,
        extra_info: Optional[Dict] = None
) -> bool:
    """保存分析结果到数据库

    Args:
        db: 数据库会话
        stock_code: 股票代码
        stock_name: 股票名称
        dimension: 分析维度
        ai_response: AI分析结果
        reasoning_process: 推理过程
        references: 参考资料列表
        extra_info: 额外信息

    Returns:
        bool: 是否保存成功
    """
    try:
        # 检查是否已存在相同维度的分析结果
        existing_result = db.query(GpFundamentalAnalysis).filter(
            GpFundamentalAnalysis.stock_code == stock_code,
            GpFundamentalAnalysis.dimension == dimension
        ).first()

        if existing_result:
            # 如果存在，则更新
            existing_result.ai_response = ai_response
            existing_result.reasoning_process = reasoning_process
            existing_result.references = references
            existing_result.extra_info = extra_info
            existing_result.update_time = datetime.now()
            db.commit()
            return True

        # 如果不存在，则创建新记录
        new_result = GpFundamentalAnalysis(
            stock_code=stock_code,
            stock_name=stock_name,
            dimension=dimension,
            ai_response=ai_response,
            reasoning_process=reasoning_process,
            references=references,
            extra_info=extra_info,
            update_time=datetime.now()
        )

        db.add(new_result)
        db.commit()
        return True

    except Exception as e:
        logger.error(f"保存分析结果失败: {str(e)}")
        db.rollback()
        return False


def get_analysis_result(db: Session, stock_code: str, dimension: str):
    """获取特定股票特定维度的分析结果"""
    try:
        result = db.query(GpFundamentalAnalysis).filter(
            GpFundamentalAnalysis.stock_code == stock_code,
            GpFundamentalAnalysis.dimension == dimension
        ).first()
        return result
    except Exception as e:
        logger.error(f"获取分析结果失败: {str(e)}")
        return None


def update_analysis_result(
        db: Session,
        stock_code: str,
        dimension: str,
        ai_response: str,
        reasoning_process: Optional[str] = None,
        references: Optional[List[Dict]] = None,
        extra_info: Optional[Dict] = None
) -> bool:
    """更新分析结果"""
    try:
        result = get_analysis_result(db, stock_code, dimension)
        if result:
            result.ai_response = ai_response
            result.reasoning_process = reasoning_process
            result.references = references
            result.extra_info = extra_info
            result.update_time = datetime.now()
            db.commit()
            return True
        return False
    except Exception as e:
        logger.error(f"更新分析结果失败: {str(e)}")
        db.rollback()
        return False 