"""Building + MapLevel models: which drawing renders an asset, at what size.

See ADR-017. A site used to have one floor map, described by four settings, and
`assets.mapx`/`mapy` were pixels in that one image. A second level and a likely
second building make that a table rather than a setting.

The alternative - stacking levels on one tall canvas - was rejected because it
turns "which level is this on" into `mapy > 2550`: an inference over a magic
number that changes whenever the drawing is re-exported.
"""

from shopdb.extensions import db
from .base import BaseModel


class Building(BaseModel):
    """A building at this site. Groups levels; holds nothing a level needs.

    Separate from Location deliberately (ADR-017): a Location answers which
    operation owns an asset, a building groups the drawings it appears on.
    """
    __tablename__ = 'buildings'

    buildingid = db.Column(db.Integer, primary_key=True)
    buildingname = db.Column(db.String(100), nullable=False, unique=True)
    # Display order. Buildings have no natural ordering and their names are not
    # reliably ordinal ('Main', 'Annex', 'Building 2'), so the order is stated.
    sortorder = db.Column(db.Integer, nullable=False, default=0)

    levels = db.relationship(
        'MapLevel', back_populates='building',
        order_by='MapLevel.sortorder', cascade='all, delete-orphan')

    def __repr__(self):
        return f"<Building {self.buildingname}>"

    def to_dict(self):
        data = super().to_dict()
        data['levels'] = [level.to_dict() for level in self.levels
                          if level.isactive]
        return data


class MapLevel(BaseModel):
    """One drawing: a level of a building, with its own blueprint and size.

    WHY THE DIMENSIONS LIVE HERE. They were site-wide settings, which cannot
    express a mezzanine drawn at a different scale from the floor below it, and
    certainly not a second building. `mapx`/`mapy` are absolute pixels in THIS
    level's coordinate space, so a level without its own dimensions cannot place
    a marker correctly.

    Name and order are separate columns on purpose: levels are not reliably
    numbered (basement, ground, mezzanine, roof), and `sortorder` gives
    adjacency and up/down navigation without pretending the names are ordinal.
    It also lets a mezzanine be inserted later without renumbering anything.
    """
    __tablename__ = 'maplevels'

    levelid = db.Column(db.Integer, primary_key=True)
    buildingid = db.Column(
        db.Integer, db.ForeignKey('buildings.buildingid'), nullable=False,
        index=True)
    levelname = db.Column(db.String(100), nullable=False)
    sortorder = db.Column(db.Integer, nullable=False, default=0)

    # Both themes, because the map renders in whichever the viewer is using and
    # a light-on-white blueprint is unreadable in dark mode. Either may be
    # blank; the renderer falls back to the other rather than to nothing.
    blueprintlight = db.Column(db.String(255), nullable=True)
    blueprintdark = db.Column(db.String(255), nullable=True)

    # Native pixel size of the blueprint. Positions are absolute pixels in this
    # space (ADR-017), so these are what a marker's coordinates mean.
    mapwidth = db.Column(db.Integer, nullable=False, default=3300)
    mapheight = db.Column(db.Integer, nullable=False, default=2550)

    # Exactly one level carries this. It is where an asset with no level lands,
    # and what the map opens on. Enforced in the API rather than by a constraint,
    # because "exactly one" across rows is not a column-level rule.
    isdefault = db.Column(db.Boolean, nullable=False, default=False)

    building = db.relationship('Building', back_populates='levels')

    __table_args__ = (
        db.UniqueConstraint('buildingid', 'levelname',
                            name='uq_maplevel_building_name'),
    )

    def __repr__(self):
        return f"<MapLevel {self.levelname}>"

    def to_dict(self):
        data = super().to_dict()
        data['buildingname'] = self.building.buildingname if self.building else None
        return data

    @classmethod
    def default_level(cls):
        """The default level, or the lowest-sorted one if none is marked.

        Never returns None on a seeded database: the migration that created this
        table also created one level from the settings it replaced.
        """
        level = cls.query.filter_by(isdefault=True, isactive=True).first()
        if level is not None:
            return level
        return (cls.query.filter_by(isactive=True)
                .order_by(cls.sortorder, cls.levelid).first())
