"""
MD to HTML Site Generator 測試

這些測試確保：
1. 基本 HTML 產生功能正常
2. 首頁包含必要元素
3. 文件頁包含必要元素
4. 搜尋功能正常
5. 筆記系統正常
6. 版本號顯示正確
"""
import sys
sys.stdout.reconfigure(encoding='utf-8')

import pytest
from pathlib import Path
import re


class TestBasicGeneration:
    """基本 HTML 產生功能測試"""

    def test_can_import_module(self, generator_module):
        """測試模組可以正常載入"""
        assert generator_module is not None
        assert hasattr(generator_module, 'INDEX_TEMPLATE')
        assert hasattr(generator_module, 'DOC_TEMPLATE')

    def test_templates_are_valid_html(self, generator_module):
        """測試模板是有效的 HTML"""
        index = generator_module.INDEX_TEMPLATE
        doc = generator_module.DOC_TEMPLATE

        # 檢查基本 HTML 結構
        assert '<!DOCTYPE html>' in index
        assert '<!DOCTYPE html>' in doc
        assert '<html' in index
        assert '</html>' in index
        assert '<html' in doc
        assert '</html>' in doc

    def test_extract_title_from_md(self, generator_module, sample_md_files):
        """測試從 Markdown 提取標題"""
        md_file = sample_md_files / "測試文件.md"
        title = generator_module.extract_title_from_md(md_file)
        assert title == "測試文件標題"

    def test_extract_description_from_md(self, generator_module, sample_md_files):
        """測試從 Markdown 提取描述"""
        md_file = sample_md_files / "測試文件.md"
        desc = generator_module.extract_description_from_md(md_file)
        assert "測試內容" in desc


class TestIndexPage:
    """首頁測試"""

    def test_index_has_search_box(self, generator_module):
        """測試首頁有搜尋框"""
        index = generator_module.INDEX_TEMPLATE
        assert 'id="search-input"' in index
        assert 'search-results' in index

    def test_index_has_theme_toggle(self, generator_module):
        """測試首頁有深色模式切換"""
        index = generator_module.INDEX_TEMPLATE
        assert 'toggleTheme' in index
        assert 'theme-btn' in index

    def test_index_has_note_center(self, generator_module):
        """測試首頁有筆記中心"""
        index = generator_module.INDEX_TEMPLATE
        assert 'note-center-modal' in index
        assert 'openNoteCenter' in index

    def test_index_has_version_footer(self, generator_module):
        """測試首頁有版本號"""
        index = generator_module.INDEX_TEMPLATE
        assert 'site-footer' in index
        assert 'v1.2.0' in index


class TestDocPage:
    """文件頁測試"""

    def test_doc_has_note_system(self, generator_module):
        """測試文件頁有三層筆記系統"""
        doc = generator_module.DOC_TEMPLATE
        # 網站筆記
        assert 'site-notes' in doc
        # 文件筆記
        assert 'doc-notes' in doc
        # 段落筆記
        assert 'para-notes' in doc

    def test_doc_has_note_panel(self, generator_module):
        """測試文件頁有筆記面板"""
        doc = generator_module.DOC_TEMPLATE
        assert 'note-panel' in doc
        assert 'note-tab' in doc

    def test_doc_has_help_modal(self, generator_module):
        """測試文件頁有使用說明"""
        doc = generator_module.DOC_TEMPLATE
        assert 'help-modal' in doc
        assert 'openHelpModal' in doc

    def test_doc_has_export_modal(self, generator_module):
        """測試文件頁有匯出功能"""
        doc = generator_module.DOC_TEMPLATE
        assert 'export-modal' in doc
        assert 'doExportNotes' in doc

    def test_doc_has_scroll_to_handler(self, generator_module):
        """測試文件頁有跳轉功能"""
        doc = generator_module.DOC_TEMPLATE
        assert 'handleScrollTo' in doc
        assert 'scrollTo' in doc
        assert 'note-highlight' in doc

    def test_doc_has_version_footer(self, generator_module):
        """測試文件頁有版本號"""
        doc = generator_module.DOC_TEMPLATE
        assert 'site-footer' in doc
        assert 'v1.2.0' in doc


class TestNoteSystem:
    """筆記系統測試"""

    def test_note_saves_page_title(self, generator_module):
        """測試筆記儲存時包含頁面標題"""
        doc = generator_module.DOC_TEMPLATE
        # saveDocNote 應該包含 pageTitle
        assert 'pageTitle: pageTitle' in doc or 'pageTitle:' in doc

    def test_note_saves_context(self, generator_module):
        """測試段落筆記儲存時包含上下文"""
        doc = generator_module.DOC_TEMPLATE
        # saveParaNote 應該包含 context
        assert 'context: currentParaContext' in doc or 'context:' in doc

    def test_note_center_collects_all_notes(self, generator_module):
        """測試筆記中心可以收集所有頁面的筆記"""
        index = generator_module.INDEX_TEMPLATE
        assert 'collectAllNotes' in index
        assert 'allDocNotes' in index
        assert 'allParaNotes' in index


class TestSearchFunction:
    """搜尋功能測試"""

    def test_search_index_is_embedded(self, generator_module):
        """測試搜尋索引會嵌入 HTML"""
        index = generator_module.INDEX_TEMPLATE
        assert 'searchIndex' in index

    def test_search_has_keyboard_shortcut(self, generator_module):
        """測試搜尋有快捷鍵"""
        index = generator_module.INDEX_TEMPLATE
        # Ctrl+K 快捷鍵
        assert "ctrlKey" in index or "metaKey" in index


class TestThemeSupport:
    """深色模式支援測試"""

    def test_has_dark_theme_css(self, generator_module):
        """測試有深色模式 CSS"""
        doc = generator_module.DOC_TEMPLATE
        assert '[data-theme="dark"]' in doc

    def test_theme_persisted_in_localstorage(self, generator_module):
        """測試主題設定會存在 localStorage"""
        index = generator_module.INDEX_TEMPLATE
        assert "localStorage" in index
        assert "'theme'" in index


class TestVersionInfo:
    """版本資訊測試"""

    def test_version_format(self, generator_module):
        """測試版本號格式正確"""
        index = generator_module.INDEX_TEMPLATE
        doc = generator_module.DOC_TEMPLATE

        # 應該是 semantic versioning 格式
        version_pattern = r'v\d+\.\d+\.\d+'
        assert re.search(version_pattern, index), "首頁應有版本號"
        assert re.search(version_pattern, doc), "文件頁應有版本號"


class TestModularFeatures:
    """模組化功能測試"""

    def test_feature_modules_defined(self, generator_module):
        """測試功能模組已定義"""
        assert hasattr(generator_module, 'FEATURE_MODULES')
        modules = generator_module.FEATURE_MODULES

        # 檢查必要的功能模組
        assert 'notes' in modules
        assert 'note_center' in modules
        assert 'search' in modules
        assert 'dark_mode' in modules
        assert 'export' in modules

    def test_feature_modules_have_required_fields(self, generator_module):
        """測試功能模組包含必要欄位"""
        modules = generator_module.FEATURE_MODULES

        for name, config in modules.items():
            assert 'name' in config, f"{name} 缺少 name 欄位"
            assert 'desc' in config, f"{name} 缺少 desc 欄位"
            assert 'depends' in config, f"{name} 缺少 depends 欄位"
            assert 'default' in config, f"{name} 缺少 default 欄位"

    def test_resolve_dependencies(self, generator_module):
        """測試依賴解析功能"""
        resolve = generator_module.resolve_dependencies

        # note_center 依賴 notes
        features = resolve(['note_center'])
        assert 'notes' in features, "note_center 應自動加入 notes 依賴"
        assert 'note_center' in features

        # export 依賴 notes
        features = resolve(['export'])
        assert 'notes' in features, "export 應自動加入 notes 依賴"

    def test_process_template_keeps_enabled_features(self, generator_module):
        """測試 process_template 保留啟用的功能"""
        process = generator_module.process_template

        template = '''
        <!-- FEATURE:search -->
        <div>搜尋功能</div>
        <!-- /FEATURE:search -->
        <div>其他內容</div>
        '''

        result = process(template, ['search'])
        assert '搜尋功能' in result
        assert '其他內容' in result

    def test_process_template_removes_disabled_features(self, generator_module):
        """測試 process_template 移除停用的功能"""
        process = generator_module.process_template

        template = '''
        <!-- FEATURE:search -->
        <div>搜尋功能</div>
        <!-- /FEATURE:search -->
        <div>其他內容</div>
        '''

        result = process(template, ['dark_mode'])  # 不包含 search
        assert '搜尋功能' not in result
        assert '其他內容' in result

    def test_process_template_handles_multiple_features(self, generator_module):
        """測試 process_template 處理多個功能"""
        process = generator_module.process_template

        template = '''
        <!-- FEATURE:search -->搜尋<!-- /FEATURE:search -->
        <!-- FEATURE:dark_mode -->深色<!-- /FEATURE:dark_mode -->
        <!-- FEATURE:notes -->筆記<!-- /FEATURE:notes -->
        '''

        # 只啟用 search 和 notes
        result = process(template, ['search', 'notes'])
        assert '搜尋' in result
        assert '筆記' in result
        assert '深色' not in result

    def test_default_features_list(self, generator_module):
        """測試預設功能列表"""
        defaults = generator_module.DEFAULT_FEATURES

        # 預設應該啟用所有功能
        for name, config in generator_module.FEATURE_MODULES.items():
            if config['default']:
                assert name in defaults, f"{name} 應在預設功能中"

    def test_index_template_has_feature_markers(self, generator_module):
        """測試首頁模板包含功能標記"""
        index = generator_module.INDEX_TEMPLATE

        # 檢查有功能標記存在
        assert '<!-- FEATURE:search -->' in index
        assert '<!-- /FEATURE:search -->' in index
        assert '<!-- FEATURE:dark_mode -->' in index
        assert '<!-- FEATURE:note_center -->' in index
