from database.database import db

class TrainingProjectDetails(db.Model):
    __tablename__ = 'training_project_details'
    
    id = db.Column(db.Integer, primary_key=True, unique=True, autoincrement=True)
    project_id = db.Column(db.Integer, db.ForeignKey('training_project.project_id', ondelete='CASCADE'), nullable=False, unique=True)
    description_text = db.Column(db.Text)  # Renamed from 'description' JSON to plain text
    
    # Relationships (3NF)
    annotation_mappings = db.relationship('AnnotationProjectMapping', backref='project_details', lazy=True, cascade='all, delete-orphan')
    class_mappings = db.relationship('ClassMapping', backref='project_details', lazy=True, cascade='all, delete-orphan')
    
    def to_dict(self, include_mappings=True):
        result = {
            'id': self.id,
            'project_id': self.project_id,
            'description': self.description_text
        }
        
        # Include mappings for backwards compatibility
        if include_mappings:
            from models.AnnotationProjectMapping import AnnotationProjectMapping
            from models.ClassMapping import ClassMapping
            
            # Get annotation projects as array
            mappings = AnnotationProjectMapping.query.filter_by(project_details_id=self.id).all()
            result['annotation_projects'] = [m.label_studio_project_id for m in mappings]
            
            # Get class map as dictionary (grouped by label_studio_project_id for backwards compatibility)
            # Return format: {source: target} (flattened across all projects)
            class_maps = ClassMapping.query.filter_by(project_details_id=self.id).all()
            result['class_map'] = {cm.source_class: cm.target_class for cm in class_maps}
        
        return result
