import enum
from datetime import datetime
from typing import List

from sqlalchemy.orm import Mapped, mapped_column, relationship

from app.brm.brn import BRN
from app.extensions import db
from app.models import AbstractConfiguration, AbstractResource
from app.models.base import Pool


class ProviderAllocation(enum.Enum):
    RANDOM = "random"
    COST = "cost"


class BridgeConf(AbstractConfiguration):
    pool_id: Mapped[int] = mapped_column(db.Integer, db.ForeignKey("pool.id"))
    method: Mapped[str]
    target_number: Mapped[int]
    max_number: Mapped[int]
    expiry_hours: Mapped[int]
    provider_allocation: Mapped[ProviderAllocation]

    pool: Mapped[Pool] = relationship("Pool", back_populates="bridgeconfs")
    bridges: Mapped[List["Bridge"]] = relationship("Bridge", back_populates="conf")

    @property
    def brn(self) -> BRN:
        return BRN(
            group_id=self.group_id,
            product="bridge",
            provider="",
            resource_type="bridgeconf",
            resource_id=str(self.id)
        )

    def destroy(self) -> None:
        self.destroyed = datetime.utcnow()
        self.updated = datetime.utcnow()
        for bridge in self.bridges:
            if bridge.destroyed is None:
                bridge.destroyed = datetime.utcnow()
                bridge.updated = datetime.utcnow()

    @classmethod
    def csv_header(cls) -> List[str]:
        return super().csv_header() + [
            "pool_id", "provider", "method", "description", "target_number", "max_number", "expiry_hours"
        ]


class Bridge(AbstractResource):
    conf_id = db.Column(db.Integer, db.ForeignKey("bridge_conf.id"), nullable=False)
    cloud_account_id = db.Column(db.Integer, db.ForeignKey("cloud_account.id"))
    terraform_updated = db.Column(db.DateTime(), nullable=True)
    nickname = db.Column(db.String(255), nullable=True)
    fingerprint = db.Column(db.String(255), nullable=True)
    hashed_fingerprint = db.Column(db.String(255), nullable=True)
    bridgeline = db.Column(db.String(255), nullable=True)

    conf = db.relationship("BridgeConf", back_populates="bridges")
    cloud_account = db.relationship("CloudAccount", back_populates="bridges")

    @property
    def brn(self) -> BRN:
        return BRN(
            group_id=0,
            product="bridge",
            provider=self.cloud_account.provider.key,
            resource_type="bridge",
            resource_id=str(self.id)
        )

    @classmethod
    def csv_header(cls) -> List[str]:
        return super().csv_header() + [
            "conf_id", "terraform_updated", "nickname", "fingerprint", "hashed_fingerprint", "bridgeline"
        ]
