#!/usr/bin/env python3
"""
Comprehensive DataDocs Documentation Validation Test

This script validates all documented features in phase-08-datadocs.md
by testing actual implementations.

Author: Test Automation
Date: 2026-01-11
"""

from __future__ import annotations

import sys
import tempfile
from pathlib import Path
from datetime import datetime
from dataclasses import dataclass

# Test results tracking
@dataclass
class TestResult:
    name: str
    passed: bool
    message: str
    category: str

results: list[TestResult] = []


def record_test(name: str, passed: bool, message: str, category: str) -> None:
    """Record a test result."""
    results.append(TestResult(name=name, passed=passed, message=message, category=category))
    status = "✅ PASS" if passed else "❌ FAIL"
    print(f"  {status}: {name}")
    if not passed:
        print(f"         {message}")


def print_summary() -> None:
    """Print test summary."""
    print("\n" + "=" * 70)
    print("TEST SUMMARY")
    print("=" * 70)

    # Group by category
    categories = {}
    for r in results:
        if r.category not in categories:
            categories[r.category] = {"passed": 0, "failed": 0}
        if r.passed:
            categories[r.category]["passed"] += 1
        else:
            categories[r.category]["failed"] += 1

    total_passed = sum(c["passed"] for c in categories.values())
    total_failed = sum(c["failed"] for c in categories.values())

    for cat, counts in categories.items():
        print(f"\n{cat}:")
        print(f"  Passed: {counts['passed']}, Failed: {counts['failed']}")

    print(f"\n{'=' * 70}")
    print(f"TOTAL: {total_passed} passed, {total_failed} failed")
    print(f"{'=' * 70}")

    # List failures
    failures = [r for r in results if not r.passed]
    if failures:
        print("\nFailed Tests:")
        for f in failures:
            print(f"  - [{f.category}] {f.name}: {f.message}")

    return total_failed == 0


# ============================================
# 1. Pipeline-Based Report Engine Tests
# ============================================
def test_pipeline_engine():
    """Test Pipeline-Based Report Engine (Section 1 of docs)."""
    print("\n" + "-" * 50)
    print("1. Pipeline-Based Report Engine")
    print("-" * 50)

    # Test 1.1: Import ReportPipeline, PipelineBuilder, ReportContext, ReportData
    try:
        from truthound.datadocs.engine import (
            ReportPipeline,
            PipelineBuilder,
            ReportContext,
            ReportData,
        )
        record_test("Import engine components", True, "", "Pipeline Engine")
    except ImportError as e:
        record_test("Import engine components", False, str(e), "Pipeline Engine")
        return

    # Test 1.2: Create ReportData
    try:
        data = ReportData(
            raw={"test": "value"},
            metadata={"title": "Test Report"},
        )
        assert data.raw == {"test": "value"}
        assert data.metadata["title"] == "Test Report"
        record_test("Create ReportData", True, "", "Pipeline Engine")
    except Exception as e:
        record_test("Create ReportData", False, str(e), "Pipeline Engine")

    # Test 1.3: Create ReportContext with from_profile
    try:
        profile_data = {
            "title": "Quality Report",
            "row_count": 1000,
            "column_count": 10,
        }
        ctx = ReportContext.from_profile(profile_data, locale="ko", theme="enterprise")
        assert ctx.locale == "ko"
        assert ctx.theme == "enterprise"
        assert ctx.data.metadata["title"] == "Quality Report"
        record_test("ReportContext.from_profile()", True, "", "Pipeline Engine")
    except Exception as e:
        record_test("ReportContext.from_profile()", False, str(e), "Pipeline Engine")

    # Test 1.4: ReportContext fluent methods
    try:
        ctx = ReportContext(data=ReportData())
        ctx2 = ctx.with_locale("ja").with_theme("dark").with_option("page_size", "A4")
        assert ctx2.locale == "ja"
        assert ctx2.theme == "dark"
        assert ctx2.get_option("page_size") == "A4"
        record_test("ReportContext fluent methods", True, "", "Pipeline Engine")
    except Exception as e:
        record_test("ReportContext fluent methods", False, str(e), "Pipeline Engine")

    # Test 1.5: PipelineBuilder
    try:
        pipeline = (
            PipelineBuilder()
            .set_theme("default")
            .set_renderer("jinja")
            .set_exporter("html")
            .build()
        )
        assert pipeline is not None
        record_test("PipelineBuilder basic usage", True, "", "Pipeline Engine")
    except Exception as e:
        record_test("PipelineBuilder basic usage", False, str(e), "Pipeline Engine")

    # Test 1.6: Pipeline generate
    try:
        ctx = ReportContext.from_profile({"title": "Test"}, locale="en")
        result = pipeline.generate(ctx)
        assert result.success
        assert result.format == "html"
        assert len(result.content) > 0
        record_test("Pipeline.generate()", True, "", "Pipeline Engine")
    except Exception as e:
        record_test("Pipeline.generate()", False, str(e), "Pipeline Engine")

    # Test 1.7: PipelineResult.save()
    try:
        with tempfile.NamedTemporaryFile(suffix=".html", delete=False) as f:
            temp_path = f.name
        result.save(temp_path)
        assert Path(temp_path).exists()
        assert Path(temp_path).stat().st_size > 0
        Path(temp_path).unlink()
        record_test("PipelineResult.save()", True, "", "Pipeline Engine")
    except Exception as e:
        record_test("PipelineResult.save()", False, str(e), "Pipeline Engine")


# ============================================
# 2. Multi-Language Reports (i18n) Tests
# ============================================
def test_i18n():
    """Test Multi-Language Reports (Section 2 of docs)."""
    print("\n" + "-" * 50)
    print("2. Multi-Language Reports (i18n)")
    print("-" * 50)

    # Test 2.1: Import i18n components
    try:
        from truthound.datadocs.i18n import (
            get_catalog,
            pluralize,
            format_number,
            format_date,
        )
        record_test("Import i18n components", True, "", "i18n")
    except ImportError as e:
        record_test("Import i18n components", False, str(e), "i18n")
        return

    # Test 2.2: Get Korean catalog
    try:
        catalog = get_catalog("ko")
        title = catalog.get("report.title")
        assert title == "데이터 품질 보고서", f"Got: {title}"
        record_test("Korean catalog - report.title", True, "", "i18n")
    except Exception as e:
        record_test("Korean catalog - report.title", False, str(e), "i18n")

    # Test 2.3: Get English catalog
    try:
        catalog = get_catalog("en")
        title = catalog.get("report.title")
        assert title == "Data Quality Report", f"Got: {title}"
        record_test("English catalog - report.title", True, "", "i18n")
    except Exception as e:
        record_test("English catalog - report.title", False, str(e), "i18n")

    # Test 2.4: Pluralize (documented says Russian pluralize returns "5 файлов")
    # Note: The doc example says `pluralize(5, "file", "files", "ru")  # "5 файлов"`
    # But the actual pluralize function takes singular/plural forms, not locale-specific forms
    try:
        result = pluralize(1, "file", "files", "en")
        assert result == "1 file", f"Got: {result}"
        result = pluralize(5, "file", "files", "en")
        assert result == "5 files", f"Got: {result}"
        record_test("pluralize() - English", True, "", "i18n")
    except Exception as e:
        record_test("pluralize() - English", False, str(e), "i18n")

    # Test 2.5: Format number with German locale (documented: "1.234.567,89")
    try:
        result = format_number(1234567.89, "de")
        # German uses . for thousands and , for decimal
        assert "." in result or "," in result, f"Got: {result}"
        record_test("format_number() - German locale", True, "", "i18n")
    except Exception as e:
        record_test("format_number() - German locale", False, str(e), "i18n")

    # Test 2.6: Format date
    try:
        dt = datetime(2025, 12, 28)
        result = format_date(dt, "ko")
        assert "2025" in result
        record_test("format_date() - Korean locale", True, "", "i18n")
    except Exception as e:
        record_test("format_date() - Korean locale", False, str(e), "i18n")

    # Test 2.7: Get supported locales (docs say 15+ formatting locales)
    try:
        from truthound.datadocs.i18n import get_supported_locales
        locales = get_supported_locales()
        # Docs claim 15 formatting locales, but catalog locales should be 2+ (en, ko)
        assert len(locales) >= 2, f"Only {len(locales)} locales found"
        assert "en" in locales
        assert "ko" in locales
        record_test(f"Supported locales: {len(locales)}", True, "", "i18n")
    except Exception as e:
        record_test("Supported locales", False, str(e), "i18n")

    # Test 2.8: CLDR plural rules
    try:
        from truthound.datadocs.i18n import get_plural_category, PluralCategory

        # English: 1=one, others=other
        assert get_plural_category(1, "en") == PluralCategory.ONE
        assert get_plural_category(5, "en") == PluralCategory.OTHER

        # Russian: complex plural rules
        assert get_plural_category(1, "ru") == PluralCategory.ONE
        assert get_plural_category(2, "ru") == PluralCategory.FEW
        assert get_plural_category(5, "ru") == PluralCategory.MANY

        record_test("CLDR plural rules", True, "", "i18n")
    except Exception as e:
        record_test("CLDR plural rules", False, str(e), "i18n")


# ============================================
# 3. White-Labeling & Enterprise Themes Tests
# ============================================
def test_themes():
    """Test White-Labeling & Enterprise Themes (Section 3 of docs)."""
    print("\n" + "-" * 50)
    print("3. White-Labeling & Enterprise Themes")
    print("-" * 50)

    # Test 3.1: Import theme components
    try:
        from truthound.datadocs.themes import (
            EnterpriseTheme,
            BrandingConfig,
            EnterpriseThemeConfig,
            ThemeColors,
        )
        record_test("Import theme components", True, "", "Themes")
    except ImportError as e:
        record_test("Import theme components", False, str(e), "Themes")
        return

    # Test 3.2: Create EnterpriseTheme directly (Method 1 from docs)
    try:
        theme = EnterpriseTheme(
            company_name="ACME Corp",
            primary_color="#1a73e8",
            logo_url="https://acme.com/logo.png",
            copyright_text="© 2025 ACME Corp",
        )
        assert theme.company_name == "ACME Corp"
        record_test("EnterpriseTheme direct creation", True, "", "Themes")
    except Exception as e:
        record_test("EnterpriseTheme direct creation", False, str(e), "Themes")

    # Test 3.3: Create EnterpriseTheme with from_config (Method 2 from docs)
    try:
        branding = BrandingConfig(
            company_name="ACME Corp",
            logo_url="https://acme.com/logo.png",
            copyright_text="© 2025 ACME Corp",
            website_url="https://acme.com",
        )
        config = EnterpriseThemeConfig(
            name="acme",
            branding=branding,
            colors=ThemeColors(primary="#1a73e8", secondary="#4f46e5"),
        )
        theme = EnterpriseTheme.from_config(config)
        assert theme.company_name == "ACME Corp"
        record_test("EnterpriseTheme.from_config()", True, "", "Themes")
    except Exception as e:
        record_test("EnterpriseTheme.from_config()", False, str(e), "Themes")

    # Test 3.4: Theme get_css()
    try:
        css = theme.get_css()
        assert len(css) > 0
        record_test("Theme.get_css()", True, "", "Themes")
    except Exception as e:
        record_test("Theme.get_css()", False, str(e), "Themes")

    # Test 3.5: Built-in themes (6 themes mentioned in docs)
    try:
        from truthound.datadocs.themes import (
            DefaultTheme,
            LightTheme,
            DarkTheme,
            MinimalTheme,
            ModernTheme,
            ProfessionalTheme,
        )
        themes = [DefaultTheme, LightTheme, DarkTheme, MinimalTheme, ModernTheme, ProfessionalTheme]
        for theme_cls in themes:
            t = theme_cls()
            assert t.get_css() is not None
        record_test(f"6 built-in themes exist", True, "", "Themes")
    except Exception as e:
        record_test("Built-in themes", False, str(e), "Themes")

    # Test 3.6: Theme customization methods
    try:
        theme = EnterpriseTheme(company_name="Test")
        new_theme = theme.with_branding(company_name="New Company")
        assert new_theme.company_name == "New Company"

        color_theme = theme.with_colors(primary="#FF0000")
        record_test("Theme customization methods", True, "", "Themes")
    except Exception as e:
        record_test("Theme customization methods", False, str(e), "Themes")

    # Test 3.7: get_theme() function
    try:
        from truthound.datadocs.themes import get_theme
        theme = get_theme("dark")
        assert theme is not None
        record_test("get_theme() function", True, "", "Themes")
    except Exception as e:
        record_test("get_theme() function", False, str(e), "Themes")


# ============================================
# 4. Optimized PDF Export Tests
# ============================================
def test_pdf_export():
    """Test Optimized PDF Export (Section 4 of docs)."""
    print("\n" + "-" * 50)
    print("4. Optimized PDF Export")
    print("-" * 50)

    # Test 4.1: Import PDF components
    try:
        from truthound.datadocs.exporters import OptimizedPdfExporter, PdfOptions
        record_test("Import PDF components", True, "", "PDF Export")
    except ImportError as e:
        record_test("Import PDF components", False, str(e), "PDF Export")
        return

    # Test 4.2: PdfOptions dataclass
    try:
        options = PdfOptions(
            dpi=150,
            image_quality=85,
            font_embedding=True,
            optimize=True,
        )
        assert options.dpi == 150
        assert options.image_quality == 85
        record_test("PdfOptions dataclass", True, "", "PDF Export")
    except Exception as e:
        record_test("PdfOptions dataclass", False, str(e), "PDF Export")

    # Test 4.3: OptimizedPdfExporter instantiation
    try:
        exporter = OptimizedPdfExporter(
            chunk_size=50,
            parallel=True,
            max_workers=4,
        )
        assert exporter is not None
        record_test("OptimizedPdfExporter instantiation", True, "", "PDF Export")
    except Exception as e:
        record_test("OptimizedPdfExporter instantiation", False, str(e), "PDF Export")

    # Test 4.4: OptimizedPdfExporter with options
    try:
        options = PdfOptions(dpi=150, image_quality=85)
        exporter = OptimizedPdfExporter(options=options)
        assert exporter.pdf_options.dpi == 150
        record_test("OptimizedPdfExporter with PdfOptions", True, "", "PDF Export")
    except Exception as e:
        record_test("OptimizedPdfExporter with PdfOptions", False, str(e), "PDF Export")

    # Test 4.5: PDF export (requires weasyprint - optional dependency)
    try:
        from truthound.datadocs.engine import ReportContext, ReportData
        ctx = ReportContext(data=ReportData(metadata={"title": "Test"}))
        html = "<html><body><h1>Test</h1></body></html>"

        try:
            pdf_bytes = exporter.export(html, ctx)
            assert isinstance(pdf_bytes, bytes)
            record_test("PDF export (WeasyPrint available)", True, "", "PDF Export")
        except ImportError:
            # WeasyPrint is an optional dependency - this is expected behavior
            record_test("PDF export (WeasyPrint is optional)", True,
                       "WeasyPrint not installed - install with: pip install weasyprint", "PDF Export")
        except Exception as inner_e:
            if "WeasyPrint is required" in str(inner_e):
                record_test("PDF export (WeasyPrint is optional)", True,
                           "WeasyPrint not installed - install with: pip install weasyprint", "PDF Export")
            else:
                record_test("PDF export", False, str(inner_e), "PDF Export")
    except Exception as e:
        record_test("PDF export", False, str(e), "PDF Export")


# ============================================
# 5. Custom Template Renderers Tests
# ============================================
def test_custom_renderers():
    """Test Custom Template Renderers (Section 5 of docs)."""
    print("\n" + "-" * 50)
    print("5. Custom Template Renderers")
    print("-" * 50)

    # Test 5.1: Import renderer components
    try:
        from truthound.datadocs.renderers import (
            JinjaRenderer,
            FileTemplateRenderer,
            StringTemplateRenderer,
            CallableRenderer,
        )
        record_test("Import renderer components", True, "", "Renderers")
    except ImportError as e:
        record_test("Import renderer components", False, str(e), "Renderers")
        return

    # Test 5.2: JinjaRenderer (documented with template_dirs as list)
    try:
        renderer = JinjaRenderer(template_dirs=[Path("./templates")])
        assert renderer is not None
        record_test("JinjaRenderer instantiation", True, "", "Renderers")
    except Exception as e:
        record_test("JinjaRenderer instantiation", False, str(e), "Renderers")

    # Test 5.3: JinjaRenderer render
    try:
        from truthound.datadocs.engine import ReportContext, ReportData
        ctx = ReportContext(
            data=ReportData(
                metadata={"title": "Test Report"},
                sections={"overview": {"count": 100}},
            )
        )
        html = renderer.render(ctx, None)
        assert "<html" in html.lower()
        record_test("JinjaRenderer.render()", True, "", "Renderers")
    except Exception as e:
        record_test("JinjaRenderer.render()", False, str(e), "Renderers")

    # Test 5.4: StringTemplateRenderer
    try:
        renderer = StringTemplateRenderer(
            template="<html><body><h1>{title}</h1></body></html>"
        )
        from truthound.datadocs.engine import ReportContext, ReportData
        ctx = ReportContext(data=ReportData(metadata={"title": "My Title"}))
        html = renderer.render(ctx, None)
        assert "My Title" in html
        record_test("StringTemplateRenderer", True, "", "Renderers")
    except Exception as e:
        record_test("StringTemplateRenderer", False, str(e), "Renderers")

    # Test 5.5: CallableRenderer
    try:
        def my_render(ctx, theme):
            return f"<html><body>{ctx.title}</body></html>"

        renderer = CallableRenderer(render_func=my_render)
        ctx = ReportContext(data=ReportData(metadata={"title": "Callable Test"}))
        html = renderer.render(ctx, None)
        assert "Callable Test" in html
        record_test("CallableRenderer", True, "", "Renderers")
    except Exception as e:
        record_test("CallableRenderer", False, str(e), "Renderers")

    # Test 5.6: FileTemplateRenderer (documented with template_path and engine)
    try:
        # Create temp template file
        with tempfile.NamedTemporaryFile(mode='w', suffix='.html', delete=False) as f:
            f.write("<html><body>{title}</body></html>")
            temp_path = f.name

        renderer = FileTemplateRenderer(
            template_path=temp_path,
            engine="string",
        )
        assert renderer is not None
        Path(temp_path).unlink()
        record_test("FileTemplateRenderer instantiation", True, "", "Renderers")
    except Exception as e:
        record_test("FileTemplateRenderer instantiation", False, str(e), "Renderers")


# ============================================
# 6. Report Versioning Tests
# ============================================
def test_versioning():
    """Test Report Versioning (Section 6 of docs)."""
    print("\n" + "-" * 50)
    print("6. Report Versioning")
    print("-" * 50)

    # Test 6.1: Import versioning components
    try:
        from truthound.datadocs.versioning import (
            FileVersionStorage,
            IncrementalStrategy,
            SemanticStrategy,
            TimestampStrategy,
            GitLikeStrategy,
            ReportDiffer,
        )
        record_test("Import versioning components", True, "", "Versioning")
    except ImportError as e:
        record_test("Import versioning components", False, str(e), "Versioning")
        return

    # Test 6.2: IncrementalStrategy
    try:
        strategy = IncrementalStrategy()
        v1 = strategy.next_version(None)
        assert v1 == 1
        v2 = strategy.next_version(v1)
        assert v2 == 2
        assert strategy.format_version(2) == "2"
        record_test("IncrementalStrategy", True, "", "Versioning")
    except Exception as e:
        record_test("IncrementalStrategy", False, str(e), "Versioning")

    # Test 6.3: SemanticStrategy
    try:
        strategy = SemanticStrategy()
        v1 = strategy.next_version(None)
        formatted = strategy.format_version(v1)
        assert "." in formatted  # Should be like "1.0.0"
        record_test("SemanticStrategy", True, "", "Versioning")
    except Exception as e:
        record_test("SemanticStrategy", False, str(e), "Versioning")

    # Test 6.4: TimestampStrategy
    try:
        strategy = TimestampStrategy()
        v1 = strategy.next_version(None)
        formatted = strategy.format_version(v1)
        # Should be ISO format
        datetime.fromisoformat(formatted)
        record_test("TimestampStrategy", True, "", "Versioning")
    except Exception as e:
        record_test("TimestampStrategy", False, str(e), "Versioning")

    # Test 6.5: GitLikeStrategy
    try:
        strategy = GitLikeStrategy()
        v1 = strategy.next_version(None, {"content": "test content"})
        formatted = strategy.format_version(v1)
        # Should be hex string
        int(formatted, 16)
        record_test("GitLikeStrategy", True, "", "Versioning")
    except Exception as e:
        record_test("GitLikeStrategy", False, str(e), "Versioning")

    # Test 6.6: FileVersionStorage (documented usage)
    try:
        with tempfile.TemporaryDirectory() as tmpdir:
            storage = FileVersionStorage(tmpdir, strategy=IncrementalStrategy())

            # Save version
            version = storage.save(
                report_id="daily_report",
                content="<html>Report v1</html>",
                message="Daily quality check",
            )

            assert version.info.version == 1
            assert version.info.message == "Daily quality check"

            # Save another version
            version2 = storage.save(
                report_id="daily_report",
                content="<html>Report v2</html>",
                message="Updated report",
            )
            assert version2.info.version == 2

            # Load version
            loaded = storage.load("daily_report", 1)
            assert loaded is not None
            assert "v1" in loaded.content

            # List versions
            versions = storage.list_versions("daily_report")
            assert len(versions) == 2

        record_test("FileVersionStorage full workflow", True, "", "Versioning")
    except Exception as e:
        record_test("FileVersionStorage full workflow", False, str(e), "Versioning")

    # Test 6.7: ReportDiffer
    try:
        differ = ReportDiffer()
        # The differ.compare method expects ReportVersion objects
        from truthound.datadocs.versioning import ReportVersion, VersionInfo

        v1 = ReportVersion(
            info=VersionInfo(version=1, report_id="test", created_at=datetime.now()),
            content="<html>Old</html>",
        )
        v2 = ReportVersion(
            info=VersionInfo(version=2, report_id="test", created_at=datetime.now()),
            content="<html>New</html>",
        )
        result = differ.compare(v1, v2)
        assert result is not None
        record_test("ReportDiffer.compare()", True, "", "Versioning")
    except Exception as e:
        record_test("ReportDiffer.compare()", False, str(e), "Versioning")


# ============================================
# 7. I18n Transformer Tests
# ============================================
def test_i18n_transformer():
    """Test I18n Transformer for pipeline."""
    print("\n" + "-" * 50)
    print("7. I18n Transformer")
    print("-" * 50)

    # Test 7.1: Import I18nTransformer
    try:
        from truthound.datadocs.transformers import I18nTransformer
        record_test("Import I18nTransformer", True, "", "Transformers")
    except ImportError as e:
        record_test("Import I18nTransformer", False, str(e), "Transformers")
        return

    # Test 7.2: Create I18nTransformer with locale
    try:
        transformer = I18nTransformer(locale="ko")
        assert transformer is not None
        record_test("I18nTransformer(locale='ko')", True, "", "Transformers")
    except Exception as e:
        record_test("I18nTransformer(locale='ko')", False, str(e), "Transformers")

    # Test 7.3: Use transformer in pipeline (as documented)
    try:
        from truthound.datadocs.engine import PipelineBuilder, ReportContext

        pipeline = (
            PipelineBuilder()
            .add_transformer(I18nTransformer(locale="ko"))
            .set_theme("professional")
            .set_exporter("html")
            .build()
        )

        ctx = ReportContext.from_profile({"title": "Test"}, locale="ko")
        result = pipeline.generate(ctx)
        assert result.success
        record_test("I18nTransformer in pipeline", True, "", "Transformers")
    except Exception as e:
        record_test("I18nTransformer in pipeline", False, str(e), "Transformers")


# ============================================
# 8. Directory Structure Validation
# ============================================
def test_directory_structure():
    """Validate documented directory structure exists."""
    print("\n" + "-" * 50)
    print("8. Directory Structure Validation")
    print("-" * 50)

    base_path = Path(__file__).parent.parent / "src" / "truthound" / "datadocs"

    documented_dirs = [
        "engine",
        "transformers",
        "renderers",
        "themes",
        "exporters",
        "versioning",
        "i18n",
    ]

    for dir_name in documented_dirs:
        dir_path = base_path / dir_name
        exists = dir_path.exists() and dir_path.is_dir()
        record_test(f"Directory: {dir_name}/", exists,
                   f"Missing: {dir_path}" if not exists else "",
                   "Directory Structure")


# ============================================
# 9. Documentation Discrepancy Checks
# ============================================
def test_doc_discrepancies():
    """Check for potential documentation discrepancies."""
    print("\n" + "-" * 50)
    print("9. Documentation Discrepancy Checks")
    print("-" * 50)

    # Check 9.1: pluralize correctly selects plural form (fixed doc)
    # Doc now says: pluralize(5, "файл", "файлов", "ru")  # "5 файлов"
    try:
        from truthound.datadocs.i18n import pluralize
        # With Russian words input, should select correct form
        result = pluralize(5, "файл", "файлов", "ru")
        if result == "5 файлов":
            record_test("Doc: pluralize selects correct Russian form", True, "", "Doc Discrepancy")
        else:
            record_test("Doc: pluralize selects correct Russian form", False,
                       f"Expected '5 файлов' but got '{result}'",
                       "Doc Discrepancy")
    except Exception as e:
        record_test("Doc: pluralize selects correct Russian form", False, str(e), "Doc Discrepancy")

    # Check 9.2: Doc correctly distinguishes between:
    # - Report translation catalogs: 2 (en, ko)
    # - Formatting locales: 15 (en, ko, ja, zh, de, fr, es, pt, it, ru, ar, th, vi, id, tr)
    # get_supported_locales() returns formatting locales which is 15
    try:
        from truthound.datadocs.i18n import get_supported_locales
        locales = get_supported_locales()
        # Doc now correctly states: 15 formatting locales
        if len(locales) >= 15:
            record_test(f"Doc: 15 formatting locales (found {len(locales)})", True, "", "Doc Discrepancy")
        else:
            record_test("Doc: 15 formatting locales", False,
                       f"Expected 15+ locales, but found {len(locales)}: {locales}",
                       "Doc Discrepancy")
    except Exception as e:
        record_test("Doc: 15 formatting locales", False, str(e), "Doc Discrepancy")

    # Check 9.3: Doc says 6 built-in themes but check actual
    try:
        from truthound.datadocs.themes import list_themes
        themes = list_themes()
        if len(themes) >= 6:
            record_test(f"Doc: 6 built-in themes (found {len(themes)})", True, "", "Doc Discrepancy")
        else:
            record_test("Doc: 6 built-in themes", False,
                       f"Doc says 6 themes but found {len(themes)}",
                       "Doc Discrepancy")
    except Exception as e:
        record_test("Doc: 6 built-in themes", False, str(e), "Doc Discrepancy")

    # Check 9.4: Doc shows format_number with German locale returns "1.234.567,89"
    try:
        from truthound.datadocs.i18n import format_number
        result = format_number(1234567.89, "de")
        expected = "1.234.567,89"
        if result == expected:
            record_test("Doc: German number format", True, "", "Doc Discrepancy")
        else:
            record_test("Doc: German number format", False,
                       f"Doc says '{expected}' but got '{result}'",
                       "Doc Discrepancy")
    except Exception as e:
        record_test("Doc: German number format", False, str(e), "Doc Discrepancy")


def main():
    """Run all tests."""
    print("=" * 70)
    print("DataDocs Documentation Validation Test")
    print("=" * 70)
    print(f"Date: {datetime.now().isoformat()}")

    # Run all test categories
    test_pipeline_engine()
    test_i18n()
    test_themes()
    test_pdf_export()
    test_custom_renderers()
    test_versioning()
    test_i18n_transformer()
    test_directory_structure()
    test_doc_discrepancies()

    # Print summary
    success = print_summary()

    return 0 if success else 1


if __name__ == "__main__":
    sys.exit(main())
