from datetime import datetime

from sqlalchemy import Boolean, Column, DateTime, Integer, String, Text
from sqlalchemy.orm import relationship

from database import Base


class Kontakt(Base):
    __tablename__ = "kontakt"

    id = Column(Integer, primary_key=True, autoincrement=True)
    cobra_id = Column(String(50), unique=True, nullable=True)
    typ = Column(String(20), nullable=False, default="person")  # person / organisation

    # Person
    anrede = Column(String(50))
    titel = Column(String(50))
    vorname = Column(String(100))
    nachname = Column(String(100))
    briefanrede = Column(String(200))

    # Organisation
    firmenname = Column(String(200))
    firmenname2 = Column(String(200))

    # Adresse
    strasse = Column(String(200))
    plz = Column(String(10))
    ort = Column(String(100))
    land = Column(String(50), default="Deutschland")

    # Kontaktdaten
    email1 = Column(String(200))
    email2 = Column(String(200))
    telefon = Column(String(50))
    telefon_direkt = Column(String(50))
    mobil = Column(String(50))
    telefax = Column(String(50))
    webseite = Column(String(200))

    # Org-Kontext (bei Personen)
    position = Column(String(200))
    abteilung = Column(String(200))

    # Meta
    bemerkung = Column(Text)
    eigentuemer = Column(String(10))
    betreuer = Column(String(10))

    # Kommunikations-Praeferenzen
    newsletter = Column(Boolean, default=False, nullable=False, server_default="0")
    keine_mails = Column(Boolean, default=False, nullable=False, server_default="0")
    keine_briefe = Column(Boolean, default=False, nullable=False, server_default="0")
    keine_anrufe = Column(Boolean, default=False, nullable=False, server_default="0")

    # Blacklist (DSGVO)
    ist_blacklisted = Column(Boolean, default=False, nullable=False, server_default="0")
    blacklist_grund = Column(String(500))
    blacklist_am = Column(DateTime)
    blacklist_von = Column(String(10))

    # Datenpflege
    zuletzt_aufgeraeumt = Column(DateTime, nullable=True)

    # Audit
    erfasst_am = Column(DateTime, default=datetime.now)
    erfasst_von = Column(String(10))
    aktualisiert_am = Column(DateTime, default=datetime.now, onupdate=datetime.now)
    aktualisiert_von = Column(String(10))

    # Relationships
    aktivitaeten = relationship("Aktivitaet", back_populates="kontakt", cascade="all, delete-orphan")
    tags = relationship("KontaktTag", back_populates="kontakt", cascade="all, delete-orphan")
    gruppen = relationship("KontaktGruppe", back_populates="kontakt", cascade="all, delete-orphan")
    spenden = relationship("Spende", back_populates="kontakt", cascade="all, delete-orphan")
    dokumente = relationship("Dokument", back_populates="kontakt", cascade="all, delete-orphan")

    beziehungen_a = relationship("Beziehung", foreign_keys="Beziehung.kontakt_a_id", back_populates="kontakt_a", cascade="all, delete-orphan")
    beziehungen_b = relationship("Beziehung", foreign_keys="Beziehung.kontakt_b_id", back_populates="kontakt_b", cascade="all, delete-orphan")

    teilnahmen = relationship("Teilnehmer", back_populates="kontakt", cascade="all, delete-orphan")
    kampagnen = relationship("KampagneKontakt", back_populates="kontakt", cascade="all, delete-orphan")
    branchen = relationship("KontaktBranche", back_populates="kontakt", cascade="all, delete-orphan")

    @property
    def anzeigename(self):
        if self.typ == "organisation":
            return self.firmenname or "Unbenannte Organisation"
        teile = [self.titel, self.vorname, self.nachname]
        return " ".join(t for t in teile if t) or "Unbenannter Kontakt"

    @property
    def kurzname(self):
        if self.typ == "organisation":
            return self.firmenname or ""
        return f"{self.vorname or ''} {self.nachname or ''}".strip()

    @property
    def branche_namen(self):
        return [kb.branche.name for kb in self.branchen if kb.branche] if self.branchen else []

    @property
    def alle_beziehungen(self):
        return self.beziehungen_a + self.beziehungen_b

    def __repr__(self):
        return f"<Kontakt {self.id}: {self.anzeigename}>"
