# -*- coding: utf-8 -*-
"""DokoGen — Модели данных (только 152-ФЗ, только нужные поля)"""

from dataclasses import dataclass, field, asdict
from typing import List, Dict, Any


@dataclass
class CommissionMember:
    """Член комиссии по ПДн"""
    role: str = "член комиссии"
    position: str = ""
    fio: str = ""


@dataclass
class InformationSystem:
    """Информационная система (обработка ПДн)"""
    name: str = ""
    description: str = ""
    is_local_network: bool = False
    is_internet: bool = False
    defence_level: str = ""
    threat_type: str = "3"
    category: str = ""
    pd_list: str = ""
    pd_count: str = "менее 100 000"
    users: str = ""
    defense_tools_list: List[str] = field(default_factory=list)
    processing_modes: str = ""
    subject_type: str = "работники организации"
    pd_actions_list: List[str] = field(default_factory=list)
    pd_subjects_list: List[str] = field(default_factory=list)
    personal_data_list: List[str] = field(default_factory=list)
    users_list: List[str] = field(default_factory=list)
    personal_data_category: List[str] = field(default_factory=list)
    purpose: str = ""
    room: str = ""
    structure: str = ""  # Структура информационной системы
    software: str = ""   # Программное обеспечение


@dataclass
class PaperDocument:
    """Бумажный документ с ПДн"""
    name: str = ""
    storage: str = ""


@dataclass
class Company:
    """Организация — основной объект (152-ФЗ)"""
    # Полное название
    full_name: str = ""
    company_name_1: str = ""  # именительный
    company_name_2: str = ""  # родительный
    company_name_3: str = ""  # дательный
    company_name_4: str = ""  # винительный
    company_name_5: str = ""  # творительный
    company_name_6: str = ""  # предложный

    # Краткое название
    short_name: str = ""
    short_name_1: str = ""
    short_name_2: str = ""
    short_name_3: str = ""
    short_name_4: str = ""
    short_name_5: str = ""
    short_name_6: str = ""

    # Адрес и реквизиты
    address: str = ""
    city_name: str = ""
    inn: str = ""
    ogrn: str = ""
    ogrn_date: str = ""
    kpp: str = ""

    # Должностные лица
    chief_position: str = ""
    chief_fio: str = ""
    responsible_position: str = ""
    responsible_fio: str = ""
    admin_position: str = ""
    admin_fio: str = ""

    # Документ
    contract_number: str = ""
    contract_date: str = ""

    # Списки
    commission: List[CommissionMember] = field(default_factory=list)
    information_systems: List[InformationSystem] = field(default_factory=list)
    paper_documents_list: List[PaperDocument] = field(default_factory=list)
    employees_access: List[Dict[str, str]] = field(default_factory=list)

    # Наименование структурного подразделения по безопасности
    security_department: str = ""

    def update_declensions(self, inflect_func):
        """Обновить склонения полного названия"""
        if self.full_name:
            inflected = inflect_func(self.full_name)
            self.company_name_1 = self.full_name
            self.company_name_2 = inflected.get("gent", "")
            self.company_name_3 = inflected.get("datv", "")
            self.company_name_4 = inflected.get("accs", "")
            self.company_name_5 = inflected.get("ablt", "")
            self.company_name_6 = inflected.get("loct", "")

    def update_short_declensions(self, inflect_func):
        """Обновить склонения сокращённого названия"""
        if self.short_name:
            inflected = inflect_func(self.short_name)
            self.short_name_1 = self.short_name
            self.short_name_2 = inflected.get("gent", "")
            self.short_name_3 = inflected.get("datv", "")
            self.short_name_4 = inflected.get("accs", "")
            self.short_name_5 = inflected.get("ablt", "")
            self.short_name_6 = inflected.get("loct", "")

    def to_dict(self) -> Dict[str, Any]:
        return asdict(self)

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "Company":
        d = dict(data)
        if "commission" in d and isinstance(d["commission"], list):
            d["commission"] = [
                CommissionMember(**c) if isinstance(c, dict) else c
                for c in d["commission"]
            ]
        if "information_systems" in d and isinstance(d["information_systems"], list):
            d["information_systems"] = [
                InformationSystem(**isys) if isinstance(isys, dict) else isys
                for isys in d["information_systems"]
            ]
        if "paper_documents_list" in d and isinstance(d["paper_documents_list"], list):
            d["paper_documents_list"] = [
                PaperDocument(**p) if isinstance(p, dict) else p
                for p in d["paper_documents_list"]
            ]
        if "employees_access" in d and not isinstance(d["employees_access"], list):
            d["employees_access"] = []
        valid = {f.name for f in cls.__dataclass_fields__.values()}
        return cls(**{k: v for k, v in d.items() if k in valid})

    def get_folder_name(self) -> str:
        if self.short_name:
            return self.short_name
        if self.full_name:
            return self.full_name[:30]
        return "Новая_организация"
