"""
Создание демо-постов для тестирования SeaBot
Используется когда реальные парсеры не работают
"""

import asyncio
import random
from datetime import datetime, timedelta
from src.database.db import session_scope
from src.database.models import Source, Post, PostMetrics
from src.metrics.calculator import MetricsCalculator

# Demo content about real estate (ASCII only for Windows compatibility)
DEMO_POSTS = [
    "New apartment in the city center! 3 rooms, 120 sq.m, panoramic windows. Price reduced!",
    "House by the sea in premium location. Private beach, 5 bedrooms, swimming pool.",
    "Real estate investment: how to earn 20% per year from rental.",
    "New business-class building! Completion in 6 months. Interest-free installment!",
    "5 mistakes when buying your first apartment. Don't repeat them!",
    "Real estate market in 2026: expert forecasts and trends.",
    "How to choose an apartment for rent? Complete guide.",
    "Mortgage at 1%! Find out how to get a preferential rate.",
    "Penthouse with 200 sq.m terrace! Exclusive offer.",
    "Premium cottage village. Ready infrastructure.",
    "Housing prices increased by 15% per year. Market analysis.",
    "Villa on the coast with ocean view. Paradise place!",
    "Safe real estate transaction: checklist for the buyer.",
    "Townhouse 200 sq.m with garage for 2 cars. Quiet area!",
    "Smart home: technologies of the future today!",
    "Commercial real estate: office 500 sq.m in business center.",
    "House in the forest: eco-style and modern comfort.",
    "Top 5 areas for real estate investment in 2026.",
    "How to correctly assess the value of an apartment? Expert advice.",
    "Profitable investment! Apartments with guaranteed income.",
]


def generate_random_metrics(base_followers: int):
    """Генерация случайных, но реалистичных метрик"""
    # Engagement rate обычно 1-5% от подписчиков
    engagement_rate = random.uniform(0.01, 0.05)
    base_engagement = int(base_followers * engagement_rate)
    
    # Распределение метрик
    views = random.randint(base_engagement * 5, base_engagement * 20)
    likes = random.randint(int(base_engagement * 0.3), int(base_engagement * 0.8))
    comments = random.randint(int(likes * 0.05), int(likes * 0.15))
    shares = random.randint(int(likes * 0.02), int(likes * 0.1))
    
    return views, likes, comments, shares


async def create_demo_posts():
    """Создание демо-постов в базе данных"""
    
    print("=" * 50)
    print("Sozdanie DEMO-postov dlya testirovaniya")
    print("=" * 50)
    
    with session_scope() as session:
        # Получить или создать демо-источники
        demo_sources = []
        
        # Instagram демо-источники
        instagram_accounts = [
            ("luxury_real_estate_demo", 500000),
            ("modern_homes_demo", 300000),
            ("property_investment_demo", 200000),
        ]
        
        for username, followers in instagram_accounts:
            source = session.query(Source).filter_by(
                platform='instagram',
                username=username
            ).first()
            
            if not source:
                source = Source(
                    platform='instagram',
                    username=username,
                    identifier=username,
                    subscriber_count=followers,
                    followers_count=followers,
                    is_active=1
                )
                session.add(source)
                session.flush()
                print(f"+ Sozdan demo-istochnik: instagram/@{username} ({followers:,} podpischikov)")
            
            demo_sources.append(source)
        
        # Создать посты за последние 3 дня
        total_posts = 0
        now = datetime.now()
        
        for source in demo_sources:
            # Создать 5-10 постов на источник
            num_posts = random.randint(5, 10)
            
            for i in range(num_posts):
                # Случайное время в последние 3 дня
                hours_ago = random.randint(1, 72)
                created_at = now - timedelta(hours=hours_ago)
                parsed_at = now
                
                # Случайный контент
                content = random.choice(DEMO_POSTS)
                
                # Уникальный ID
                external_id = f"demo_{source.username}_{int(created_at.timestamp())}_{i}"
                
                # Проверить, не существует ли уже
                existing = session.query(Post).filter_by(
                    source_id=source.id,
                    external_id=external_id
                ).first()
                
                if existing:
                    continue
                
                # Генерация метрик
                views, likes, comments, shares = generate_random_metrics(source.subscriber_count)
                
                # Создать пост
                post = Post(
                    source_id=source.id,
                    external_id=external_id,
                    content=content,
                    url=f"https://www.instagram.com/p/{external_id}/",
                    views=views,
                    reactions=0,
                    likes=likes,
                    comments=comments,
                    shares=shares,
                    created_at=created_at,
                    parsed_at=parsed_at
                )
                session.add(post)
                session.flush()
                
                # Calculate metrics
                try:
                    # Check if metrics already exist
                    existing_metrics = session.query(PostMetrics).filter_by(post_id=post.id).first()
                    
                    if not existing_metrics:
                        metrics = MetricsCalculator.calculate_post_metrics(post, source)
                        metrics.post_id = post.id
                        session.add(metrics)
                        
                        print(
                            f"  + Post created: {content[:40]}... "
                            f"(views={views:,}, likes={likes:,}, score={metrics.normalized_score:.2f})"
                        )
                    else:
                        print(f"  = Post already exists: {content[:40]}...")
                    
                    total_posts += 1
                except Exception as e:
                    print(f"  ! Error calculating metrics: {e}")
                    # Check if empty metrics already exist
                    existing_metrics = session.query(PostMetrics).filter_by(post_id=post.id).first()
                    if not existing_metrics:
                        empty_metrics = PostMetrics(
                            post_id=post.id,
                            engagement_rate=0.0,
                            normalized_score=0.0,
                            subscriber_ratio=0.0,
                            total_engagement=0,
                            calculated_at=datetime.now()
                        )
                        session.add(empty_metrics)
        
        print("=" * 50)
        print(f"+ Sozdano {total_posts} demo-postov")
        print("=" * 50)
        print("\nTeper vy mozhete protestirovat bota:")
        print("   - /top — Top za segodnya")
        print("   - /top_yesterday — Top za vchera")
        print("   - /stats — Statistika po istochnikam")
        print("=" * 50)


if __name__ == "__main__":
    asyncio.run(create_demo_posts())
