from pathlib import Path

import yaml
from django.conf import settings
from django.db.utils import OperationalError, ProgrammingError


def governance_defaults() -> dict:
    return {
        "owner_mappings": [
            {
                "owner_role": "注册资料负责人",
                "owner_name": "张三",
                "department": "注册事务部",
                "chapter_scope": "CH1",
                "risk_scope": "字段冲突 / 缺失项",
                "feishu_user_id": "ou_demo_1",
                "feishu_open_id": "on_demo_1",
                "feishu_name": "张三",
                "notify_enabled": "是",
            },
            {
                "owner_role": "注册申报负责人",
                "owner_name": "李四",
                "department": "临床注册组",
                "chapter_scope": "CH2-CH6",
                "risk_scope": "完整性风险 / 导出阻断",
                "feishu_user_id": "ou_demo_2",
                "feishu_open_id": "on_demo_2",
                "feishu_name": "李四",
                "notify_enabled": "是",
            },
        ],
        "feishu_configs": [
            {
                "config_name": "注册审核完成通知",
                "notify_reason": "task_completed",
                "channel": "群机器人",
                "message_template": "审核完成摘要 + @处理人",
                "status": "启用",
            },
            {
                "config_name": "注册审核异常通知",
                "notify_reason": "task_failed",
                "channel": "群机器人",
                "message_template": "异常摘要 + @处理人",
                "status": "启用",
            },
        ],
        "template_mappings": [
            {
                "template_name": "注册证导出模板",
                "output_type": "registration_word_export_report",
                "version": "V1.0",
                "placeholder_count": 18,
                "status": "启用",
                "field_mapping_summary": "产品名称 / 注册人 / 适用机型 / 储存条件",
            },
            {
                "template_name": "风险摘要导出模板",
                "output_type": "registration_word_export_report",
                "version": "V0.9",
                "placeholder_count": 10,
                "status": "待校验",
                "field_mapping_summary": "风险等级 / 批次号 / 责任人 / 证据摘要",
            },
        ],
    }


def read_governance_yaml() -> dict:
    raw_path = getattr(settings, "GOVERNANCE_CONFIG_PATH", "")
    if not raw_path:
        return {}
    config_path = Path(raw_path)
    if not config_path.exists() or not config_path.is_file():
        return {}
    with config_path.open("r", encoding="utf-8") as file:
        return yaml.safe_load(file) or {}


def load_governance_config() -> dict:
    defaults = governance_defaults()
    config = read_governance_yaml()
    db_config = load_governance_config_from_db()
    for key, default_value in defaults.items():
        configured_value = db_config.get(key) or config.get(key)
        if isinstance(default_value, list) and configured_value:
            defaults[key] = configured_value
    return defaults


def load_governance_config_from_db() -> dict:
    try:
        from apps.platform_ui.models import FeishuNotifyConfig, OwnerMapping, WordTemplateMapping
    except Exception:
        return {}

    try:
        owner_mappings = [
            {
                "owner_role": item.owner_role,
                "owner_name": item.owner_name,
                "department": item.department,
                "chapter_scope": item.chapter_scope,
                "risk_scope": item.risk_scope,
                "feishu_user_id": item.feishu_user_id,
                "feishu_open_id": item.feishu_open_id,
                "feishu_name": item.feishu_name,
                "notify_enabled": "是" if item.notify_enabled else "否",
            }
            for item in OwnerMapping.objects.filter(is_active=True)
        ]
        feishu_configs = [
            {
                "config_name": item.config_name,
                "notify_reason": item.notify_reason,
                "channel": item.channel,
                "message_template": item.message_template,
                "status": item.status,
            }
            for item in FeishuNotifyConfig.objects.filter(is_active=True)
        ]
        template_mappings = [
            {
                "template_name": item.template_name,
                "output_type": item.output_type,
                "version": item.version,
                "placeholder_count": item.placeholder_count,
                "status": item.status,
                "field_mapping_summary": item.field_mapping_summary,
            }
            for item in WordTemplateMapping.objects.filter(is_active=True)
        ]
    except (OperationalError, ProgrammingError, RuntimeError):
        return {}

    return {
        "owner_mappings": owner_mappings,
        "feishu_configs": feishu_configs,
        "template_mappings": template_mappings,
    }
