"""
 * @author Xiaobo Sun, Daliang Chen
 * created  on 29.11.2025
 * @copyright (C) 2025 Sogood International GmbH - all rights reserved
 * @licence
 * Unauthorized copying of this file, via any medium is strictly prohibited
 * Proprietary and confidential
"""

import json
import os
import logging
from pydantic import BaseModel, Field
from typing import List, Optional

# Get an instance of a logger
logger = logging.getLogger('django')

class GegenkontoEntry(BaseModel):
    id: int
    enabled: bool
    from_country: str = Field(alias="fromCountry")
    to_country: str = Field(alias="toCountry")
    isMerchant: bool
    konto: str
    mkonto: str
    buKey: str = Field(alias="bu-key")
    tax: str

    class Config:
        populate_by_name = True


class CompanyEntry(BaseModel):
    id: int
    beraternummer: str = Field(alias="Beraternummer")
    mandantennummer: str = Field(alias="Mandantennummer")
    enabled: bool
    name: str

    class Config:
        populate_by_name = True


class ConfigData(BaseModel):
    gegenkonto: List[GegenkontoEntry]
    company: List[CompanyEntry]


try:
    logger.info("loading datev config")
    source_path = os.path.dirname(os.path.abspath(__file__))
    with open(source_path + "/settings.json", "r", encoding="utf-8") as f:
        data_dict = json.load(f)

    config_object = ConfigData(**data_dict)
except Exception as e:
    print(f"Failed to load config: {e}")


def load_config(file_path) -> Optional[ConfigData]:
    logger.info("datev load_config")
    if not os.path.exists(file_path):
        print(f"File not found: {file_path}")
        return None

    try:
        with open(file_path, "r", encoding="utf-8") as f:
            data_dict = json.load(f)

        config_instance = ConfigData(**data_dict)
        return config_instance

    except Exception as e:
        print(f"Failed to load config: {e}")
        return None

CONFIG: Optional[ConfigData] = load_config(source_path + "/settings.json")