from django.urls import reverse
from django.test import override_settings
from django.contrib import admin

from apps.platform_ui.services import get_platform_demo_context
from apps.platform_ui.models import FeishuNotifyConfig, OwnerMapping, WordTemplateMapping


def test_knowledge_base_page_shows_governance_sections(client):
    response = client.get(reverse("platform_ui:knowledge-base"))

    content = response.content.decode("utf-8")
    assert response.status_code == 200
    assert "法规规则包" in content
    assert "RAG 文档源" in content
    assert "RAG 切片" in content
    assert "字段 Schema" in content
    assert "责任人映射" in content
    assert "飞书通知配置" in content


def test_knowledge_base_page_shows_owner_mapping_fields_and_notify_reasons(client):
    response = client.get(reverse("platform_ui:knowledge-base"))

    content = response.content.decode("utf-8")
    assert response.status_code == 200
    assert "owner_role" in content
    assert "owner_name" in content
    assert "department" in content
    assert "chapter_scope" in content
    assert "risk_scope" in content
    assert "feishu_user_id" in content
    assert "feishu_open_id" in content
    assert "feishu_name" in content
    assert "notify_enabled" in content
    assert "task_completed" in content
    assert "task_failed" in content


@override_settings(GOVERNANCE_CONFIG_PATH="")
def test_get_platform_demo_context_reads_governance_yaml(tmp_path):
    config_path = tmp_path / "governance.yaml"
    config_path.write_text(
        """
owner_mappings:
  - owner_role: 临床注册负责人
    owner_name: 王五
    department: 临床事务部
    chapter_scope: CH3-CH6
    risk_scope: 高风险阻断
    feishu_user_id: ou_test_owner
    feishu_open_id: on_test_owner
    feishu_name: 王五
    notify_enabled: 是
feishu_configs:
  - config_name: Demo 完成通知
    notify_reason: task_completed
    channel: 群机器人
    message_template: 审核完成摘要 + @处理人
    status: 启用
template_mappings:
  - template_name: 注册证导出模板
    output_type: registration_word_export_report
    version: V1.0
    placeholder_count: 12
    status: 启用
    field_mapping_summary: 产品名称 / 注册人 / 适用机型
""".strip(),
        encoding="utf-8",
    )

    with override_settings(GOVERNANCE_CONFIG_PATH=config_path):
        context = get_platform_demo_context()

    assert context["owner_mappings"][0]["owner_name"] == "王五"
    assert context["feishu_configs"][0]["notify_reason"] == "task_completed"
    assert context["template_mappings"][0]["template_name"] == "注册证导出模板"
    assert context["template_mappings"][0]["field_mapping_summary"] == "产品名称 / 注册人 / 适用机型"


@override_settings(GOVERNANCE_CONFIG_PATH="")
def test_knowledge_base_page_shows_template_mappings_from_governance_config(client, tmp_path):
    config_path = tmp_path / "governance.yaml"
    config_path.write_text(
        """
template_mappings:
  - template_name: 风险摘要导出模板
    output_type: registration_word_export_report
    version: V2.0
    placeholder_count: 8
    status: 灰度中
    field_mapping_summary: 风险等级 / 产品名称 / 责任人
""".strip(),
        encoding="utf-8",
    )

    with override_settings(GOVERNANCE_CONFIG_PATH=config_path):
        response = client.get(reverse("platform_ui:knowledge-base"))

    content = response.content.decode("utf-8")
    assert response.status_code == 200
    assert "Word 模板与字段映射" in content
    assert "风险摘要导出模板" in content
    assert "风险等级 / 产品名称 / 责任人" in content


def test_get_platform_demo_context_prefers_database_governance_entries(db):
    OwnerMapping.objects.create(
        owner_role="数据库负责人",
        owner_name="周八",
        department="注册事务部",
        chapter_scope="CH5",
        risk_scope="数据库覆盖",
        feishu_user_id="ou_db_1",
        feishu_open_id="on_db_1",
        feishu_name="周八",
        notify_enabled=True,
        is_active=True,
    )
    FeishuNotifyConfig.objects.create(
        config_name="数据库通知配置",
        notify_reason="task_failed",
        channel="群机器人",
        message_template="异常摘要 + @处理人",
        status="启用",
        is_active=True,
    )
    WordTemplateMapping.objects.create(
        template_name="数据库模板",
        output_type="registration_word_export_report",
        version="V3.0",
        placeholder_count=16,
        status="启用",
        field_mapping_summary="产品名称 / 规格 / 风险等级",
        is_active=True,
    )

    context = get_platform_demo_context()

    assert context["owner_mappings"][0]["owner_name"] == "周八"
    assert context["feishu_configs"][0]["config_name"] == "数据库通知配置"
    assert context["template_mappings"][0]["template_name"] == "数据库模板"


def test_governance_models_are_registered_in_admin():
    assert OwnerMapping in admin.site._registry
    assert FeishuNotifyConfig in admin.site._registry
    assert WordTemplateMapping in admin.site._registry


def test_knowledge_base_page_shows_governance_object_navigation_and_active_panel(client):
    response = client.get(reverse("platform_ui:knowledge-base"), {"view": "owner_mappings"})

    content = response.content.decode("utf-8")
    assert response.status_code == 200
    assert "治理对象导航" in content
    assert "法规规则包" in content
    assert "RAG 文档源" in content
    assert "Word 模板与字段映射" in content
    assert "责任人映射详情" in content
    assert "当前对象：责任人映射" in content
    assert "批量导入映射" in content


def test_knowledge_base_page_exposes_governance_crud_entry_links(client):
    response = client.get(reverse("platform_ui:knowledge-base"), {"view": "template_mappings"})

    content = response.content.decode("utf-8")
    assert response.status_code == 200
    assert "上传模板" in content
    assert "编辑占位符映射" in content
    assert "预览模板" in content
    assert reverse("admin:platform_ui_wordtemplatemapping_changelist") in content


def test_knowledge_base_page_shows_governance_action_hub_and_fixed_notify_policy(client):
    response = client.get(reverse("platform_ui:knowledge-base"), {"view": "feishu_configs"})

    content = response.content.decode("utf-8")
    assert response.status_code == 200
    assert "治理动作总览" in content
    assert "当前治理对象" in content
    assert "进入审核智能体" in content
    assert "查看资料包" in content
    assert "查看处理历史" in content
    assert "固定通知策略" in content
    assert "task_completed" in content
    assert "task_failed" in content
    assert reverse("audit:list") in content
    assert reverse("documents:list") in content


def test_command_center_v2_renders_and_links_to_chat_index(client):
    response = client.get(reverse("platform_ui:command-center-v2"))

    content = response.content.decode("utf-8")
    assert response.status_code == 200
    assert "试剂盒临床注册文件准备与审核智能体平台" in content
    assert reverse("chat:index") in content


def test_command_center_v2_uses_unified_four_entry_labels(client):
    response = client.get(reverse("platform_ui:command-center-v2"))

    content = response.content.decode("utf-8")
    assert response.status_code == 200
    assert "审核智能体" in content
    assert "资料包" in content
    assert "知识库" in content
    assert "处理历史" in content
    assert "资料包管理" not in content
    assert "法规库" not in content
    assert "智能审核" not in content
    assert "统计分析" not in content


def test_command_center_v2_uses_four_product_entries_as_primary_navigation(client):
    response = client.get(reverse("platform_ui:command-center-v2"))

    content = response.content.decode("utf-8")
    assert response.status_code == 200
    assert 'aria-label="一级产品入口"' in content
    assert "一级产品" in content
    assert "协同治理" in content
    assert "审核指挥台" in content
    assert "场景配置参考" in content
    assert "任务中心" not in content
    assert "工作台</span>" not in content


def test_platform_demo_context_uses_agent_product_labels_for_quick_links():
    context = get_platform_demo_context()
    quick_links = context["quick_links"]
    titles = [item["title"] for item in quick_links]

    assert "审核智能体" in titles
    assert "审核指挥台" in titles
    assert "审核工作台" not in titles
    assert "工作台大屏" not in titles
    assert any(
        item["title"] == "审核指挥台" and item["url_name"] == "platform_ui:command-center-v2"
        for item in quick_links
    )


def test_command_center_legacy_route_redirects_to_v2(client):
    response = client.get(reverse("platform_ui:command-center"))

    assert response.status_code == 302
    assert response.url == reverse("platform_ui:command-center-v2")
