#!/usr/bin/env python3
"""
Test Title Format Functionality

This script tests that snapshot titles are properly formatted using
child forename and author forename/surname instead of post ID.
"""

import sys
import os
import tempfile
from pathlib import Path

# Add the current directory to the path so we can import modules
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from snapshot_downloader import SnapshotDownloader


class TitleFormatTester:
    """Test class for title formatting functionality."""

    def __init__(self):
        """Initialize the tester."""
        pass

    def test_title_formatting(self):
        """Test that titles are formatted correctly with child and author names."""
        print("=" * 60)
        print("TEST: Title Format - Child by Author")
        print("=" * 60)

        with tempfile.TemporaryDirectory() as temp_dir:
            downloader = SnapshotDownloader(output_dir=temp_dir)

            print("1. Testing standard title format...")

            # Test case 1: Complete data
            mock_snapshot = {
                "id": 123456,
                "type": "Snapshot",
                "child": {
                    "forename": "Noah",
                    "surname": "Smith"
                },
                "author": {
                    "forename": "Elena",
                    "surname": "Garcia"
                },
                "startTime": "2024-01-15T10:30:00",
                "notes": "<p>Test snapshot content</p>"
            }

            html_content = downloader.format_snapshot_html(mock_snapshot)
            expected_title = "Noah by Elena Garcia"

            if f'<h3 class="snapshot-title">{expected_title}</h3>' in html_content:
                print(f"   ✅ Standard format: {expected_title}")
            else:
                print(f"   ❌ Expected: {expected_title}")
                print("   Debug: Looking for title in HTML...")
                start = html_content.find('snapshot-title')
                if start != -1:
                    sample = html_content[start:start+100]
                    print(f"   Found: {sample}")
                return False

            print("\n2. Testing edge cases...")

            # Test case 2: Missing child surname
            mock_snapshot_2 = {
                "id": 789012,
                "type": "Snapshot",
                "child": {
                    "forename": "Sofia"
                    # Missing surname
                },
                "author": {
                    "forename": "Maria",
                    "surname": "Rodriguez"
                },
                "startTime": "2024-01-15T10:30:00",
                "notes": "<p>Test content</p>"
            }

            html_content_2 = downloader.format_snapshot_html(mock_snapshot_2)
            expected_title_2 = "Sofia by Maria Rodriguez"

            if f'<h3 class="snapshot-title">{expected_title_2}</h3>' in html_content_2:
                print(f"   ✅ Missing child surname: {expected_title_2}")
            else:
                print(f"   ❌ Expected: {expected_title_2}")
                return False

            # Test case 3: Missing author surname
            mock_snapshot_3 = {
                "id": 345678,
                "type": "Snapshot",
                "child": {
                    "forename": "Alex",
                    "surname": "Johnson"
                },
                "author": {
                    "forename": "Lisa"
                    # Missing surname
                },
                "startTime": "2024-01-15T10:30:00",
                "notes": "<p>Test content</p>"
            }

            html_content_3 = downloader.format_snapshot_html(mock_snapshot_3)
            expected_title_3 = "Alex by Lisa"

            if f'<h3 class="snapshot-title">{expected_title_3}</h3>' in html_content_3:
                print(f"   ✅ Missing author surname: {expected_title_3}")
            else:
                print(f"   ❌ Expected: {expected_title_3}")
                return False

            # Test case 4: Missing child forename (should fallback to ID)
            mock_snapshot_4 = {
                "id": 999999,
                "type": "Snapshot",
                "child": {
                    "surname": "Brown"
                    # Missing forename
                },
                "author": {
                    "forename": "John",
                    "surname": "Davis"
                },
                "startTime": "2024-01-15T10:30:00",
                "notes": "<p>Test content</p>"
            }

            html_content_4 = downloader.format_snapshot_html(mock_snapshot_4)
            expected_title_4 = "Snapshot 999999"

            if f'<h3 class="snapshot-title">{expected_title_4}</h3>' in html_content_4:
                print(f"   ✅ Missing child forename (fallback): {expected_title_4}")
            else:
                print(f"   ❌ Expected fallback: {expected_title_4}")
                return False

            # Test case 5: Missing author forename (should fallback to ID)
            mock_snapshot_5 = {
                "id": 777777,
                "type": "Snapshot",
                "child": {
                    "forename": "Emma",
                    "surname": "Wilson"
                },
                "author": {
                    "surname": "Taylor"
                    # Missing forename
                },
                "startTime": "2024-01-15T10:30:00",
                "notes": "<p>Test content</p>"
            }

            html_content_5 = downloader.format_snapshot_html(mock_snapshot_5)
            expected_title_5 = "Snapshot 777777"

            if f'<h3 class="snapshot-title">{expected_title_5}</h3>' in html_content_5:
                print(f"   ✅ Missing author forename (fallback): {expected_title_5}")
            else:
                print(f"   ❌ Expected fallback: {expected_title_5}")
                return False

            print("\n3. Testing HTML escaping in titles...")

            # Test case 6: Names with special characters
            mock_snapshot_6 = {
                "id": 555555,
                "type": "Snapshot",
                "child": {
                    "forename": "José",
                    "surname": "García"
                },
                "author": {
                    "forename": "María",
                    "surname": "López <script>"
                },
                "startTime": "2024-01-15T10:30:00",
                "notes": "<p>Test content</p>"
            }

            html_content_6 = downloader.format_snapshot_html(mock_snapshot_6)

            # Check that special characters are preserved but HTML is escaped
            if "José by María López" in html_content_6 and "&lt;script&gt;" in html_content_6:
                print("   ✅ Special characters preserved, HTML escaped")
            else:
                print("   ❌ Special character or HTML escaping failed")
                return False

            print("\n✅ Title formatting test completed successfully!")
            return True

    def test_complete_html_generation(self):
        """Test title formatting in complete HTML file generation."""
        print("\n" + "=" * 60)
        print("TEST: Title Format in Complete HTML File")
        print("=" * 60)

        with tempfile.TemporaryDirectory() as temp_dir:
            downloader = SnapshotDownloader(output_dir=temp_dir)

            # Create multiple snapshots with different name scenarios
            mock_snapshots = [
                {
                    "id": 100001,
                    "type": "Snapshot",
                    "child": {"forename": "Noah", "surname": "Sitaru"},
                    "author": {"forename": "Elena", "surname": "Blanco"},
                    "startTime": "2025-08-14T10:42:00",
                    "notes": "<p>Noah's progress today</p>"
                },
                {
                    "id": 100002,
                    "type": "Snapshot",
                    "child": {"forename": "Sophia", "surname": "Sitaru"},
                    "author": {"forename": "Kyra", "surname": "Philbert-Nurse"},
                    "startTime": "2025-07-31T10:42:00",
                    "notes": "<p>Sophia's activity</p>"
                },
                {
                    "id": 100003,
                    "type": "Snapshot",
                    "child": {"forename": "Emma"},  # Missing surname
                    "author": {"forename": "Lisa", "surname": "Wilson"},
                    "startTime": "2025-06-15T14:30:00",
                    "notes": "<p>Emma's development</p>"
                }
            ]

            print("1. Generating complete HTML file...")
            html_file = downloader.generate_html_file(mock_snapshots, "2024-01-01", "2024-12-31")

            if html_file.exists():
                print("   ✅ HTML file generated successfully")

                with open(html_file, 'r', encoding='utf-8') as f:
                    file_content = f.read()

                # Check for expected titles
                expected_titles = [
                    "Noah by Elena Blanco",
                    "Sophia by Kyra Philbert-Nurse",
                    "Emma by Lisa Wilson"
                ]

                print("\n2. Checking titles in generated file...")
                all_found = True
                for title in expected_titles:
                    if f'<h3 class="snapshot-title">{title}</h3>' in file_content:
                        print(f"   ✅ Found: {title}")
                    else:
                        print(f"   ❌ Missing: {title}")
                        all_found = False

                if not all_found:
                    return False

                print("\n3. Verifying HTML structure...")
                if 'class="snapshot-title"' in file_content:
                    print("   ✅ Title CSS class present")
                else:
                    print("   ❌ Title CSS class missing")
                    return False

                print("\n✅ Complete HTML file generation test passed!")
                return True
            else:
                print("   ❌ HTML file was not generated")
                return False

    def run_all_tests(self):
        """Run all title formatting tests."""
        print("🚀 Starting Title Format Tests")
        print("=" * 80)

        try:
            success = True

            success &= self.test_title_formatting()
            success &= self.test_complete_html_generation()

            if success:
                print("\n" + "=" * 80)
                print("🎉 ALL TITLE FORMAT TESTS PASSED!")
                print("=" * 80)
                print("✅ Titles formatted as 'Child by Author Name'")
                print("✅ Edge cases handled correctly (missing names)")
                print("✅ HTML escaping works for special characters")
                print("✅ Complete HTML generation includes proper titles")
                print("\n📋 Title Format Examples:")
                print("• Noah by Elena Blanco")
                print("• Sophia by Kyra Philbert-Nurse")
                print("• Emma by Lisa Wilson")
                print("• Snapshot 123456 (fallback when names missing)")
            else:
                print("\n❌ SOME TITLE FORMAT TESTS FAILED")

            return success

        except Exception as e:
            print(f"\n❌ TITLE FORMAT TESTS FAILED: {e}")
            import traceback
            traceback.print_exc()
            return False


def show_title_format_info():
    """Show information about the title format."""
    print("\n" + "=" * 80)
    print("📋 SNAPSHOT TITLE FORMAT")
    print("=" * 80)

    print("\n🎯 New Format:")
    print("Child Forename by Author Forename Surname")

    print("\n📝 Examples:")
    print("• Noah by Elena Blanco")
    print("• Sophia by Kyra Philbert-Nurse")
    print("• Alex by Maria Rodriguez")
    print("• Emma by Lisa Wilson")

    print("\n🔄 Fallback Behavior:")
    print("• Missing child forename → 'Snapshot [ID]'")
    print("• Missing author forename → 'Snapshot [ID]'")
    print("• Missing surnames → Names without surname used")

    print("\n🔒 HTML Escaping:")
    print("• Special characters preserved (José, María)")
    print("• HTML tags escaped for security (<script> → &lt;script&gt;)")
    print("• Accents and international characters supported")

    print("\n💡 Benefits:")
    print("• More meaningful snapshot identification")
    print("• Easy to scan and find specific child's snapshots")
    print("• Clear attribution to teaching staff")
    print("• Professional presentation for reports")


def main():
    """Main test function."""
    tester = TitleFormatTester()

    # Run tests
    success = tester.run_all_tests()

    # Show information
    if success:
        show_title_format_info()

    return 0 if success else 1


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