"""
Example usage of DSS Export/Import System

Run with: python -m dss.export_import.examples
"""

from pathlib import Path
from datetime import datetime
from uuid import uuid4

from ..models.project import Project, ProjectMetadata
from ..models.theme import Theme, DesignToken, TokenCategory
from ..models.component import Component

from . import (
    DSSArchiveExporter,
    DSSArchiveImporter,
    SmartMerger,
    ConflictResolutionMode,
)


def create_sample_project(name="Sample Design System") -> Project:
    """Create a sample project for testing"""

    # Create tokens
    tokens = {
        "primary": DesignToken(
            name="primary",
            value="#3B82F6",
            type="color",
            category=TokenCategory.COLOR,
            description="Primary brand color",
            source="figma:abc123",
        ),
        "space-md": DesignToken(
            name="space-md",
            value="16px",
            type="dimension",
            category=TokenCategory.SPACING,
            description="Medium spacing",
        ),
    }

    # Create theme
    theme = Theme(
        name="Light",
        version="1.0.0",
        tokens=tokens,
    )

    # Create components
    button = Component(
        name="Button",
        source="custom",
        description="Basic button component",
        variants=["primary", "secondary", "outline"],
        props={"size": ["sm", "md", "lg"], "disabled": "boolean"},
    )

    card = Component(
        name="Card",
        source="custom",
        description="Card container",
        variants=["default", "elevated"],
        props={"padding": "enum"},
    )

    # Create project
    project = Project(
        id="sample-ds",
        name=name,
        version="1.0.0",
        description="A sample design system for testing",
        theme=theme,
        components=[button, card],
        metadata=ProjectMetadata(
            author="Design Team",
            team="Design",
            tags=["sample", "demo"],
        ),
    )

    return project


def example_1_basic_export():
    """Example 1: Basic export to .dss file"""
    print("\n" + "=" * 70)
    print("EXAMPLE 1: Basic Export")
    print("=" * 70)

    # Create sample project
    project = create_sample_project("My Design System")
    print(f"✓ Created project: {project.name}")
    print(f"  - UUID: {project.uuid}")
    print(f"  - Tokens: {len(project.theme.tokens)}")
    print(f"  - Components: {len(project.components)}")

    # Export to .dss file
    output_path = Path("/tmp/my-design-system.dss")
    exporter = DSSArchiveExporter(project)
    saved_path = exporter.export_to_file(output_path)

    print(f"\n✓ Exported to: {saved_path}")
    print(f"  - File size: {saved_path.stat().st_size:,} bytes")
    print(f"  - Schema version: {exporter.manifest.schema_version}")
    print(f"  - Export timestamp: {exporter.manifest.export_timestamp}")


def example_2_archive_analysis():
    """Example 2: Analyze archive before importing"""
    print("\n" + "=" * 70)
    print("EXAMPLE 2: Archive Analysis")
    print("=" * 70)

    # Create and export
    project = create_sample_project("Analysis Test")
    output_path = Path("/tmp/analysis-test.dss")
    exporter = DSSArchiveExporter(project)
    exporter.export_to_file(output_path)

    # Analyze
    importer = DSSArchiveImporter(output_path)
    analysis = importer.analyze()

    print(f"✓ Archive analysis complete")
    print(f"  - Valid: {analysis.is_valid}")
    print(f"  - Project: {analysis.project_name}")
    print(f"  - Schema: {analysis.schema_version}")
    print(f"  - Tokens: {analysis.content_summary['tokens']['count']}")
    print(f"  - Components: {analysis.content_summary['components']['count']}")
    print(f"  - Migration needed: {analysis.migration_needed}")

    if analysis.errors:
        print(f"\n  Errors:")
        for error in analysis.errors:
            print(f"    - [{error.stage}] {error.message}")
    else:
        print(f"\n  ✓ No validation errors")


def example_3_replace_import():
    """Example 3: Import with REPLACE strategy"""
    print("\n" + "=" * 70)
    print("EXAMPLE 3: REPLACE Import (Full Restoration)")
    print("=" * 70)

    # Create and export
    original = create_sample_project("Replace Test")
    output_path = Path("/tmp/replace-test.dss")
    exporter = DSSArchiveExporter(original)
    exporter.export_to_file(output_path)

    print(f"✓ Original project exported")
    print(f"  - Tokens: {len(original.theme.tokens)}")
    print(f"  - Components: {len(original.components)}")

    # Import with REPLACE
    importer = DSSArchiveImporter(output_path)
    imported = importer.import_replace()

    print(f"\n✓ Project imported (REPLACE strategy)")
    print(f"  - Name: {imported.name}")
    print(f"  - UUID: {imported.uuid}")
    print(f"  - Tokens: {len(imported.theme.tokens)}")
    print(f"  - Components: {len(imported.components)}")

    # Verify round-trip
    assert imported.name == original.name
    assert len(imported.theme.tokens) == len(original.theme.tokens)
    assert len(imported.components) == len(original.components)
    print(f"\n✓ Round-trip verification successful")


def example_4_merge_analysis():
    """Example 4: Analyze merge without modifying"""
    print("\n" + "=" * 70)
    print("EXAMPLE 4: Merge Analysis")
    print("=" * 70)

    # Create local project
    local = create_sample_project("Local Version")
    local.theme.tokens["secondary"] = DesignToken(
        name="secondary",
        value="#10B981",
        type="color",
        category=TokenCategory.COLOR,
    )
    print(f"✓ Local project: {len(local.theme.tokens)} tokens")

    # Create and export imported version (with differences)
    imported = create_sample_project("Remote Version")
    imported.theme.tokens["accent"] = DesignToken(
        name="accent",
        value="#F59E0B",
        type="color",
        category=TokenCategory.COLOR,
    )
    output_path = Path("/tmp/merge-test.dss")
    exporter = DSSArchiveExporter(imported)
    exporter.export_to_file(output_path)
    print(f"✓ Imported project: {len(imported.theme.tokens)} tokens")

    # Analyze merge
    importer = DSSArchiveImporter(output_path)
    imported_proj = importer.import_replace()
    merger = SmartMerger(local, imported_proj)
    analysis = merger.analyze_merge()

    print(f"\n✓ Merge analysis complete")
    print(f"  - New tokens: {len(analysis.new_items['tokens'])}")
    print(f"  - Updated tokens: {len(analysis.updated_items['tokens'])}")
    print(f"  - Updated components: {len(analysis.updated_items['components'])}")
    print(f"  - Conflicts: {len(analysis.conflicted_items)}")
    print(f"  - Total changes: {analysis.total_changes}")


def example_5_merge_with_strategy():
    """Example 5: Perform merge with conflict strategy"""
    print("\n" + "=" * 70)
    print("EXAMPLE 5: Merge with Strategy")
    print("=" * 70)

    # Create local and remote versions
    local = create_sample_project("Local")
    local.theme.tokens["primary"].value = "#FF0000"  # Changed locally
    local.theme.tokens["primary"].updated_at = datetime.utcnow()

    remote = create_sample_project("Remote")
    remote.theme.tokens["primary"].value = "#00FF00"  # Changed remotely
    remote.theme.tokens["primary"].updated_at = datetime.utcnow()

    # Export and import
    output_path = Path("/tmp/merge-strategy.dss")
    exporter = DSSArchiveExporter(remote)
    exporter.export_to_file(output_path)

    importer = DSSArchiveImporter(output_path)
    imported = importer.import_replace()

    # Merge with OVERWRITE
    merger = SmartMerger(local, imported)
    merged = merger.merge_with_strategy(ConflictResolutionMode.OVERWRITE)

    print(f"✓ Merge complete (OVERWRITE strategy)")
    print(f"  - Tokens: {len(merged.theme.tokens)}")
    print(f"  - primary token value: {merged.theme.tokens['primary'].value}")
    print(f"  - (Should be remote: #00FF00)")

    # Merge with KEEP_LOCAL
    merged2 = merger.merge_with_strategy(ConflictResolutionMode.KEEP_LOCAL)
    print(f"\n✓ Merge complete (KEEP_LOCAL strategy)")
    print(f"  - primary token value: {merged2.theme.tokens['primary'].value}")
    print(f"  - (Should be local: #FF0000)")


def example_6_schema_migration():
    """Example 6: Automatic schema migration"""
    print("\n" + "=" * 70)
    print("EXAMPLE 6: Schema Migration")
    print("=" * 70)

    from .migrations import MigrationManager

    current_version = MigrationManager.get_latest_version()
    print(f"✓ Current schema version: {current_version}")
    print(f"✓ Available versions: {MigrationManager.VERSIONS}")

    # Simulate old archive data
    old_data = {
        "project": {
            "id": "old-project",
            "name": "Old Project",
            # Note: no uuid fields
        },
        "tokens": {
            "primary": {
                "$value": "#3B82F6",
                "$type": "color",
                # Note: no uuid field
            }
        },
        "components": [
            {
                "name": "Button",
                # Note: no uuid field
            }
        ],
    }

    # Migrate
    migrated = MigrationManager.migrate(
        old_data,
        from_version="1.0.0",
        to_version=current_version,
    )

    print(f"\n✓ Migration complete: 1.0.0 → {current_version}")
    print(f"  - Project UUID added: {migrated['project'].get('uuid')}")
    print(f"  - Component UUID added: {migrated['components'][0].get('uuid')}")


def main():
    """Run all examples"""
    print("\n" + "█" * 70)
    print("█ DSS Export/Import System - Usage Examples")
    print("█" * 70)

    example_1_basic_export()
    example_2_archive_analysis()
    example_3_replace_import()
    example_4_merge_analysis()
    example_5_merge_with_strategy()
    example_6_schema_migration()

    print("\n" + "█" * 70)
    print("█ All examples completed successfully!")
    print("█" * 70 + "\n")


if __name__ == "__main__":
    main()
