from sqlalchemy import create_engine, Column, Integer, String, Float, DateTime, Boolean, Text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import datetime
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DB_URL = f"sqlite:///{os.path.join(BASE_DIR, 'kis_stock.db')}"

engine = create_engine(DB_URL, connect_args={"check_same_thread": False})

# Enable WAL mode for better concurrency
from sqlalchemy import event
@event.listens_for(engine, "connect")
def set_sqlite_pragma(dbapi_connection, connection_record):
    cursor = dbapi_connection.cursor()
    cursor.execute("PRAGMA journal_mode=WAL")
    cursor.close()

SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

class Stock(Base):
    __tablename__ = "stocks"
    code = Column(String, primary_key=True, index=True)
    name = Column(String, index=True)
    name_eng = Column(String, nullable=True) # English Name
    market = Column(String) # KOSPI, KOSDAQ, NASD, NYSE, AMEX
    sector = Column(String, nullable=True)
    industry = Column(String, nullable=True) # Detailed Industry
    type = Column(String, default="DOMESTIC") # DOMESTIC, OVERSEAS
    financial_status = Column(String, nullable=True) # 'N', 'D', 'E' etc from Nasdaq
    is_etf = Column(Boolean, default=False)
    current_price = Column(Float, default=0.0)

class Watchlist(Base):
    __tablename__ = "watchlist"
    id = Column(Integer, primary_key=True, index=True)
    code = Column(String, index=True)
    name = Column(String) # Cache name for display
    market = Column(String)
    is_monitoring = Column(Boolean, default=True)
    created_at = Column(DateTime, default=datetime.datetime.now)

class Order(Base):
    __tablename__ = "orders"
    id = Column(Integer, primary_key=True, index=True)
    order_id = Column(String, nullable=True) # KIS Order ID
    code = Column(String, index=True)
    type = Column(String) # BUY, SELL
    price = Column(Float)
    quantity = Column(Integer)
    status = Column(String) # PENDING, FILLED, CANCELLED
    created_at = Column(DateTime, default=datetime.datetime.now)

class TradeSetting(Base):
    __tablename__ = "trade_settings"
    code = Column(String, primary_key=True)
    target_price = Column(Float, nullable=True)
    stop_loss_price = Column(Float, nullable=True)
    trailing_stop_percent = Column(Float, nullable=True)
    is_active = Column(Boolean, default=False)

class News(Base):
    __tablename__ = "news"
    id = Column(Integer, primary_key=True, index=True)
    title = Column(String)
    link = Column(String, unique=True)
    pub_date = Column(String)
    analysis_result = Column(Text)
    impact_score = Column(Integer)
    related_sector = Column(String)
    created_at = Column(DateTime, default=datetime.datetime.now)

class StockPrice(Base):
    __tablename__ = "stock_prices"
    id = Column(Integer, primary_key=True, index=True)
    code = Column(String, index=True)
    price = Column(Float)
    change = Column(Float)
    volume = Column(Integer)
    created_at = Column(DateTime, default=datetime.datetime.now)

class AccountBalance(Base):
    __tablename__ = "account_balance"
    id = Column(Integer, primary_key=True)
    total_eval = Column(Float, default=0.0) # 총평가금액
    deposit = Column(Float, default=0.0)    # 예수금
    total_profit = Column(Float, default=0.0) # 평가손익
    updated_at = Column(DateTime, default=datetime.datetime.now)

class Holding(Base):
    __tablename__ = "holdings"
    id = Column(Integer, primary_key=True, index=True)
    code = Column(String, index=True)
    name = Column(String)
    quantity = Column(Integer)
    price = Column(Float) # 매입평단가
    current_price = Column(Float) # 현재가
    profit_rate = Column(Float)
    market = Column(String) # DOMESTIC, NASD, etc.
    updated_at = Column(DateTime, default=datetime.datetime.now)

def init_db():
    Base.metadata.create_all(bind=engine)

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
