#!/usr/bin/env python3
"""
Iteration 1: Core Validation Test Suite
Tests all token ingestion, analysis, and Storybook functionality
"""

import asyncio
import sys
import json
from pathlib import Path

# Add tools to path
sys.path.insert(0, str(Path(__file__).parent))

async def test_css_ingestion():
    """Test CSS token ingestion"""
    print("\n=== Testing CSS Token Ingestion ===")
    from tools.ingest.css import CSSTokenSource

    # Test CSS
    css_content = """
    :root {
        --primary-color: #3B82F6;
        --spacing-md: 16px;
        --font-size-base: 16px;
    }
    """

    try:
        parser = CSSTokenSource()
        collection = await parser.extract(css_content)
        print(f"✅ CSS: Parsed {len(collection.tokens)} tokens")
        for token in collection.tokens[:3]:
            print(f"  - {token.name}: {token.value}")
        return True
    except Exception as e:
        print(f"❌ CSS Error: {e}")
        import traceback
        traceback.print_exc()
        return False

async def test_scss_ingestion():
    """Test SCSS token ingestion"""
    print("\n=== Testing SCSS Token Ingestion ===")
    from tools.ingest.scss import SCSSTokenSource

    scss_content = """
    $primary: #3B82F6;
    $spacing-md: 16px;
    $font-family: 'Inter', sans-serif;
    """

    try:
        parser = SCSSTokenSource()
        tokens = await parser.parse(scss_content)
        print(f"✅ SCSS: Parsed {len(tokens)} tokens")
        for token in tokens[:3]:
            print(f"  - {token.name}: {token.value}")
        return True
    except Exception as e:
        print(f"❌ SCSS Error: {e}")
        return False

async def test_tailwind_ingestion():
    """Test Tailwind config ingestion"""
    print("\n=== Testing Tailwind Token Ingestion ===")
    from tools.ingest.tailwind import TailwindTokenSource

    config_content = """
    module.exports = {
      theme: {
        colors: {
          primary: '#3B82F6',
          secondary: '#10B981',
        },
        spacing: {
          'sm': '8px',
          'md': '16px',
        }
      }
    }
    """

    try:
        parser = TailwindTokenSource()
        tokens = await parser.parse(config_content)
        print(f"✅ Tailwind: Parsed {len(tokens)} tokens")
        for token in tokens[:3]:
            print(f"  - {token.name}: {token.value}")
        return True
    except Exception as e:
        print(f"❌ Tailwind Error: {e}")
        return False

async def test_json_ingestion():
    """Test JSON token ingestion"""
    print("\n=== Testing JSON Token Ingestion ===")
    from tools.ingest.json_tokens import JSONTokenSource

    json_content = {
        "color": {
            "primary": {
                "500": {"value": "#3B82F6", "type": "color"}
            }
        },
        "spacing": {
            "md": {"value": "16px", "type": "dimension"}
        }
    }

    try:
        parser = JSONTokenSource()
        tokens = await parser.parse(json.dumps(json_content))
        print(f"✅ JSON: Parsed {len(tokens)} tokens")
        for token in tokens[:3]:
            print(f"  - {token.name}: {token.value}")
        return True
    except Exception as e:
        print(f"❌ JSON Error: {e}")
        return False

async def test_token_merge():
    """Test token merging"""
    print("\n=== Testing Token Merge ===")
    from tools.ingest.merge import TokenMerger, MergeStrategy
    from tools.ingest.base import DesignToken

    try:
        tokens_a = [
            DesignToken(name="color.primary", value="#FF0000", type="color", source="css"),
            DesignToken(name="spacing.md", value="16px", type="dimension", source="css"),
        ]

        tokens_b = [
            DesignToken(name="color.primary", value="#3B82F6", type="color", source="figma"),
            DesignToken(name="color.secondary", value="#10B981", type="color", source="figma"),
        ]

        merger = TokenMerger(strategy=MergeStrategy.PREFER_FIGMA)
        result = await merger.merge([tokens_a, tokens_b])

        print(f"✅ Merge: {len(result.tokens)} tokens, {len(result.conflicts)} conflicts")
        if result.conflicts:
            print(f"  Conflicts resolved:")
            for conflict in result.conflicts:
                print(f"    - {conflict.token_name}: chose {conflict.chosen_value}")
        return True
    except Exception as e:
        print(f"❌ Merge Error: {e}")
        return False

async def test_figma_tools():
    """Test Figma integration"""
    print("\n=== Testing Figma Integration ===")
    from tools.figma.figma_tools import FigmaToolSuite

    try:
        # Test with mock mode (no API key)
        suite = FigmaToolSuite(output_dir="./test_output")
        print(f"✅ Figma: Mode = {suite.mode}")

        # Test mock data
        file_key = "test123"
        components = await suite.extract_components(file_key)
        print(f"  Components: {components.get('components_count', 0)}")

        styles = await suite.extract_styles(file_key)
        print(f"  Styles: {styles.get('styles_count', 0)}")

        return True
    except Exception as e:
        print(f"❌ Figma Error: {e}")
        return False

async def main():
    """Run all tests"""
    print("=" * 60)
    print("DSS ITERATION 1: CORE VALIDATION")
    print("=" * 60)

    results = []

    # Token Ingestion Tests
    results.append(("CSS Ingestion", await test_css_ingestion()))
    results.append(("SCSS Ingestion", await test_scss_ingestion()))
    results.append(("Tailwind Ingestion", await test_tailwind_ingestion()))
    results.append(("JSON Ingestion", await test_json_ingestion()))
    results.append(("Token Merge", await test_token_merge()))
    results.append(("Figma Tools", await test_figma_tools()))

    # Summary
    print("\n" + "=" * 60)
    print("TEST SUMMARY")
    print("=" * 60)

    passed = sum(1 for _, result in results if result)
    total = len(results)

    for name, result in results:
        status = "✅ PASS" if result else "❌ FAIL"
        print(f"{status}: {name}")

    print(f"\nPassed: {passed}/{total} ({100*passed//total}%)")

    if passed == total:
        print("\n🎉 ALL TESTS PASSED!")
        return 0
    else:
        print(f"\n⚠️  {total - passed} TEST(S) FAILED")
        return 1

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