import asyncio
import sys
import os
import json
from datetime import datetime

# Fix encoding
if sys.platform == 'win32':
    os.environ['PYTHONIOENCODING'] = 'utf-8'
    if hasattr(sys.stdout, 'reconfigure'):
        sys.stdout.reconfigure(encoding='utf-8')

from src.parsers import XParser, InstagramParser
from src.parsers.base import ParsedPost

async def main():
    results = []
    results.append("=== PARSER LOGIC VERIFICATION ===")
    results.append("Note: Running with offline mock data to verify logic due to network timeouts.\n")

    # --- Test X Parser Logic ---
    results.append("1. XParser Logic Test")
    try:
        parser = XParser("TestUser", 0)
        
        # Mock GraphQL Response
        mock_response = {
            "data": {
                "user": {
                    "result": {
                        "timeline_v2": {
                            "timeline": {
                                "instructions": [
                                    {
                                        "type": "TimelineAddEntries",
                                        "entries": [
                                            {
                                                "content": {
                                                    "entryType": "TimelineTimelineItem",
                                                    "itemContent": {
                                                        "tweet_results": {
                                                            "result": {
                                                                "key": "value",
                                                                "legacy": {
                                                                    "full_text": "This is a test tweet parsed successfully!",
                                                                    "created_at": "Wed Oct 10 20:19:24 +0000 2025",
                                                                    "favorite_count": 42,
                                                                    "retweet_count": 5,
                                                                    "reply_count": 3,
                                                                    "view_count": 1000
                                                                },
                                                                "rest_id": "123456789"
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        ]
                                    }
                                ]
                            }
                        }
                    }
                }
            }
        }
        
        # Extract using the private method
        posts = parser._extract_posts_from_graphql(mock_response, datetime(2020, 1, 1))
        
        if posts:
            results.append("✅ Logic Verified: Successfully extracted posts from structure.")
            for p in posts:
                results.append(f"   Post ID: {p.external_id}")
                results.append(f"   Content: {p.content}")
                results.append(f"   Metrics: Likes={p.likes}, Views={p.views}")
        else:
            results.append("❌ Logic Failed: Could not extract posts.")
            
    except Exception as e:
        results.append(f"❌ Error: {e}")

    results.append("\n" + "-"*30 + "\n")

    # --- Test Instagram Parser Logic ---
    results.append("2. InstagramParser Logic Test")
    try:
        parser = InstagramParser("testuser", 0)
        
        # Mock GraphQL Response
        mock_ig_response = {
            "data": {
                "user": {
                    "edge_owner_to_timeline_media": {
                        "edges": [
                            {
                                "node": {
                                    "shortcode": "test_code_123",
                                    "taken_at_timestamp": 1736670000,
                                    "edge_media_to_caption": {
                                        "edges": [{"node": {"text": "A beautiful photo from testing!"}}]
                                    },
                                    "edge_liked_by": {"count": 150},
                                    "edge_media_to_comment": {"count": 20},
                                    "is_video": False
                                }
                            }
                        ]
                    }
                }
            }
        }
        
        posts = parser._extract_posts_from_graphql(mock_ig_response, datetime(2020, 1, 1))
        
        if posts:
            results.append("✅ Logic Verified: Successfully extracted posts from structure.")
            for p in posts:
                results.append(f"   ID: {p.external_id}")
                results.append(f"   Content: {p.content}")
                results.append(f"   Metrics: Likes={p.likes}, Comments={p.comments}")
        else:
            results.append("❌ Logic Failed: Could not extract posts.")
            
    except Exception as e:
        results.append(f"❌ Error: {e}")

    # Write to file
    with open('parsed_posts.txt', 'w', encoding='utf-8') as f:
        f.write('\n'.join(results))
        
    print("Verification complete. Check parsed_posts.txt")

if __name__ == '__main__':
    asyncio.run(main())
