from sqlalchemy import create_engine, Column, Integer, String, Text, Date, DateTime, ForeignKey
from sqlalchemy.orm import declarative_base, sessionmaker, relationship, scoped_session
from datetime import datetime
import os

DB_PATH = os.path.join(os.path.dirname(__file__), 'app.db')
engine = create_engine(f'sqlite:///{DB_PATH}', echo=False, future=True, pool_pre_ping=True, pool_recycle=3600)
SessionLocal = scoped_session(sessionmaker(bind=engine, autoflush=False, autocommit=False))
Base = declarative_base()

class Profile(Base):
    __tablename__ = 'profiles'
    id = Column(String(200), primary_key=True)  # Support both int and UUID strings
    name = Column(String(100), unique=True, nullable=False)
    email = Column(String(100), default='')
    contact_number = Column(String(50), default='')
    default_key = Column(String(10), default='C')
    notes = Column(Text, default='')

class Song(Base):
    __tablename__ = 'songs'
    id = Column(String(200), primary_key=True)  # Support UUID strings
    title = Column(String(200), nullable=False)
    artist = Column(String(200), default='')
    band = Column(String(200), default='')
    singer = Column(String(200), default='')
    lyrics = Column(Text, default='')
    chords = Column(Text, default='')
    created_at = Column(DateTime, default=datetime.now)
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)

class Plan(Base):
    __tablename__ = 'plans'
    id = Column(Integer, primary_key=True)
    date = Column(Date, nullable=False)
    profile_id = Column(String(200), ForeignKey('profiles.id'))
    memo = Column(Text, default='')
    profile = relationship('Profile')

class PlanSong(Base):
    __tablename__ = 'plan_songs'
    id = Column(Integer, primary_key=True)
    plan_id = Column(Integer, ForeignKey('plans.id'))
    song_id = Column(String(200), ForeignKey('songs.id'))
    order_index = Column(Integer, default=0)
    plan = relationship('Plan')
    song = relationship('Song')

class ProfileSong(Base):
    __tablename__ = 'profile_songs'
    id = Column(Integer, primary_key=True)
    profile_id = Column(String(200), ForeignKey('profiles.id'))
    song_id = Column(String(200), ForeignKey('songs.id'))
    song_key = Column(String(10), default='C')
    profile = relationship('Profile')
    song = relationship('Song')

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