from datetime import datetime
from sqlalchemy import Column, Integer, String, DateTime, ForeignKey, Boolean, JSON
from sqlalchemy.orm import relationship
from ..database import Base

class AgentNode(Base):
    __tablename__ = 'agent_nodes'

    id = Column(Integer, primary_key=True, index=True)
    node_id = Column(String, unique=True, index=True, nullable=False)
    display_name = Column(String, nullable=False)
    description = Column(String, nullable=True)
    registered_by = Column(String, ForeignKey('users.id'), nullable=False)
    skill_config = Column(JSON, default={
        "shell": {"enabled": True},
        "sync": {"enabled": True},
    }, nullable=False)
    capabilities = Column(JSON, default={}, nullable=True)
    invite_token = Column(String, unique=True, nullable=True, index=True)
    is_active = Column(Boolean, default=True, nullable=False)
    last_status = Column(String, default="offline", nullable=False)
    last_seen_at = Column(DateTime, nullable=True)
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)

    registered_by_user = relationship("User", foreign_keys=[registered_by])
    group_access = relationship("NodeGroupAccess", back_populates="node", cascade="all, delete-orphan")

    def __repr__(self):
        return f"<AgentNode(node_id='{self.node_id}', status='{self.last_status}')>"

class NodeGroupAccess(Base):
    __tablename__ = 'node_group_access'

    id = Column(Integer, primary_key=True, index=True)
    node_id = Column(String, ForeignKey('agent_nodes.node_id'), nullable=False, index=True)
    group_id = Column(String, ForeignKey('groups.id'), nullable=False, index=True)
    access_level = Column(String, default="use", nullable=False)
    granted_by = Column(String, ForeignKey('users.id'), nullable=False)
    granted_at = Column(DateTime, default=datetime.utcnow, nullable=False)

    node = relationship("AgentNode", back_populates="group_access")
    group = relationship("Group")
    granted_by_user = relationship("User", foreign_keys=[granted_by])

    def __repr__(self):
        return f"<NodeGroupAccess(node='{self.node_id}', group='{self.group_id}', level='{self.access_level}')>"
