﻿"""
Management command to load initial data from JSON files into the database.

Usage: python manage.py load_initial_data
"""
import json
from pathlib import Path
from datetime import datetime
from django.core.management.base import BaseCommand
from django.utils import timezone
from datetime import timedelta
from base.models import Bot, ForexPair, Lesson, Signal, News, Testimonial, LeaderboardEntry


class Command(BaseCommand):
    help = 'Load initial data from JSON files'

    def handle(self, *args, **options):
        """Execute the data loading."""
        base_dir = Path(__file__).resolve().parent.parent.parent.parent.parent
        data_dir = base_dir / 'assets' / 'data'

        self.stdout.write(self.style.SUCCESS(f'Loading data from {data_dir}...'))

        self.load_bots(data_dir)
        self.load_forex(data_dir)
        self.load_lessons(data_dir)
        self.load_signals(data_dir)
        self.load_news(data_dir)
        self.load_testimonials(data_dir)
        self.load_leaderboard(data_dir)

        self.stdout.write(self.style.SUCCESS('âœ“ Data loading complete!'))

    # â”€â”€ Bots â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€

    def load_bots(self, data_dir):
        """Load bots from JSON (camelCase source â†’ snake_case model)."""
        file_path = data_dir / 'bots.json'
        if not file_path.exists():
            self.stdout.write(self.style.WARNING(f'Skipping bots - {file_path} not found'))
            return

        with open(file_path, 'r', encoding='utf-8') as f:
            data = json.load(f)

        Bot.objects.all().delete()
        for item in data:
            Bot.objects.create(
                name=item['name'],
                description=item['description'],
                category=item['category'],
                pairs=item.get('pairs', []),
                timeframe=item.get('timeframe', ''),
                win_rate=item.get('winRate', item.get('win_rate', 0)),
                total_trades=item.get('totalTrades', item.get('total_trades', 0)),
                avg_profit=item.get('avgProfit', item.get('avg_profit', 0)),
                max_drawdown=item.get('maxDrawdown', item.get('max_drawdown', 0)),
                monthly_return=item.get('monthlyReturn', item.get('monthly_return', 0)),
                price=item.get('price', 0),
                plan=item.get('plan', 'Basic'),
                status=item.get('status', 'active'),
                backtest_years=item.get('backtestYears', item.get('backtest_years', 0)),
                sharpe_ratio=item.get('sharpeRatio', item.get('sharpe_ratio', 0)),
                badge=item.get('badge', ''),
                tags=item.get('tags', []),
                chart_data=item.get('chartData', item.get('chart_data', [])),
            )
        self.stdout.write(self.style.SUCCESS(f'  âœ“ Loaded {len(data)} bots'))

    # â”€â”€ Forex â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€

    def load_forex(self, data_dir):
        """Load forex pairs from JSON."""
        file_path = data_dir / 'forex.json'
        if not file_path.exists():
            self.stdout.write(self.style.WARNING(f'Skipping forex - {file_path} not found'))
            return

        with open(file_path, 'r', encoding='utf-8') as f:
            data = json.load(f)

        ForexPair.objects.all().delete()
        for item in data:
            ForexPair.objects.create(
                pair=item['pair'],
                base=item.get('base', ''),
                quote=item.get('quote', ''),
                price=item.get('price', 0),
                change=item.get('change', 0),
                change_pct=item.get('changePct', item.get('change_pct', 0)),
                bid=item.get('bid', 0),
                ask=item.get('ask', 0),
                spread=item.get('spread', 0),
                high=item.get('high', 0),
                low=item.get('low', 0),
                volume=item.get('volume', ''),
                trend=item.get('trend', 'sideways'),
                symbol1=item.get('symbol1', ''),
                symbol2=item.get('symbol2', ''),
                color1=item.get('color1', ''),
                color2=item.get('color2', ''),
                category=item.get('category', 'major'),
                sentiment=item.get('sentiment', 50),
            )
        self.stdout.write(self.style.SUCCESS(f'  âœ“ Loaded {len(data)} forex pairs'))

    # â”€â”€ Lessons â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€

    def load_lessons(self, data_dir):
        """Load lessons from JSON (organized by category key)."""
        file_path = data_dir / 'lessons.json'
        if not file_path.exists():
            self.stdout.write(self.style.WARNING(f'Skipping lessons - {file_path} not found'))
            return

        with open(file_path, 'r', encoding='utf-8') as f:
            data = json.load(f)

        Lesson.objects.all().delete()
        lesson_count = 0

        for category, lessons in data.items():
            for idx, item in enumerate(lessons):
                Lesson.objects.create(
                    title=item.get('title', ''),
                    description=item.get('description', ''),
                    category=category,
                    difficulty=item.get('module', 'beginner').lower(),
                    duration_minutes=item.get('duration', 30),
                    image_url=item.get('image_url', item.get('imageUrl', '')),
                    video_url=item.get('video_url', item.get('videoUrl', '')),
                    content=item.get('content', ''),
                    order=idx,
                    tags=item.get('topics', item.get('tags', [])),
                )
                lesson_count += 1

        self.stdout.write(self.style.SUCCESS(f'  âœ“ Loaded {lesson_count} lessons'))

    # â”€â”€ Signals â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€

    def load_signals(self, data_dir):
        """Load signals from JSON.

        JSON field mapping:
          direction (BUY/SELL) â†’ signal_type (buy/sell/hold)
          entryMin             â†’ entry_price
          stopLoss             â†’ stop_loss
          takeProfit1          â†’ take_profit
          strategy             â†’ chart_pattern
          notes                â†’ reason
        """
        file_path = data_dir / 'signals.json'
        if not file_path.exists():
            self.stdout.write(self.style.WARNING(f'Skipping signals - {file_path} not found'))
            return

        with open(file_path, 'r', encoding='utf-8') as f:
            data = json.load(f)

        Signal.objects.all().delete()
        for item in data:
            direction = item.get('direction', 'BUY').lower()
            if direction not in ('buy', 'sell', 'hold'):
                direction = 'buy'

            entry = float(item.get('entryMin', item.get('entry_price', item.get('entryPrice', 1.0))) or 1.0)
            sl = float(item.get('stopLoss', item.get('stop_loss', 1.0)) or 1.0)
            tp = float(item.get('takeProfit1', item.get('take_profit', 1.0)) or 1.0)

            Signal.objects.create(
                pair=item.get('pair', ''),
                signal_type=direction,
                confidence=item.get('confidence', 50),
                entry_price=entry,
                stop_loss=sl,
                take_profit=tp,
                reason=item.get('notes', item.get('reason', '')),
                chart_pattern=item.get('strategy', item.get('chart_pattern', '')),
                # 30-day expiry so the API always returns these signals
                expires_at=timezone.now() + timedelta(days=30),
            )
        self.stdout.write(self.style.SUCCESS(f'  âœ“ Loaded {len(data)} signals'))

    # â”€â”€ News â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€

    def load_news(self, data_dir):
        """Load news from JSON.

        JSON field mapping:
          headline â†’ title
          summary  â†’ content
          author   â†’ source
          tags     â†’ related_pairs
          date     â†’ published_at
        """
        file_path = data_dir / 'news.json'
        if not file_path.exists():
            self.stdout.write(self.style.WARNING(f'Skipping news - {file_path} not found'))
            return

        with open(file_path, 'r', encoding='utf-8') as f:
            data = json.load(f)

        News.objects.all().delete()
        for item in data:
            pub_date = timezone.now()
            date_str = item.get('date', item.get('published_at', ''))
            if date_str:
                try:
                    pub_date = datetime.fromisoformat(date_str.replace('Z', '+00:00'))
                except (ValueError, AttributeError):
                    pass

            News.objects.create(
                title=item.get('headline', item.get('title', '')),
                content=item.get('summary', item.get('content', '')),
                source=item.get('author', item.get('source', 'TheStarFX')),
                image_url=item.get('image_url', item.get('imageUrl', '')),
                category=item.get('category', 'general'),
                impact=item.get('impact', 'medium'),
                related_pairs=item.get('tags', item.get('related_pairs', [])),
                published_at=pub_date,
            )
        self.stdout.write(self.style.SUCCESS(f'  âœ“ Loaded {len(data)} news articles'))

    # â”€â”€ Testimonials â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€

    def load_testimonials(self, data_dir):
        """Load testimonials from JSON.

        JSON field mapping:
          name  â†’ author_name
          role  â†’ author_title
          text  â†’ content
        """
        file_path = data_dir / 'testimonials.json'
        if not file_path.exists():
            self.stdout.write(self.style.WARNING(f'Skipping testimonials - {file_path} not found'))
            return

        with open(file_path, 'r', encoding='utf-8') as f:
            data = json.load(f)

        Testimonial.objects.all().delete()
        for item in data:
            Testimonial.objects.create(
                author_name=item.get('name', item.get('author_name', '')),
                author_title=item.get('role', item.get('author_title', '')),
                author_image=item.get('author_image', ''),
                content=item.get('text', item.get('content', '')),
                rating=item.get('rating', 5),
            )
        self.stdout.write(self.style.SUCCESS(f'  âœ“ Loaded {len(data)} testimonials'))

    # â”€â”€ Leaderboard â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€

    def load_leaderboard(self, data_dir):
        """Load leaderboard from JSON.

        JSON field mapping:
          name        â†’ user_name
          avatar      â†’ avatar (initials like "AK")
          winRate     â†’ win_rate
          totalTrades â†’ total_trades
          profitMonth â†’ monthly_return
          profitAllTime â†’ profit
        """
        file_path = data_dir / 'leaderboard.json'
        if not file_path.exists():
            self.stdout.write(self.style.WARNING(f'Skipping leaderboard - {file_path} not found'))
            return

        with open(file_path, 'r', encoding='utf-8') as f:
            data = json.load(f)

        LeaderboardEntry.objects.all().delete()
        for item in data:
            LeaderboardEntry.objects.create(
                rank=item.get('rank', 1),
                user_name=item.get('name', item.get('user_name', '')),
                avatar=item.get('avatar', ''),
                monthly_return=item.get('profitMonth', item.get('monthly_return', 0)),
                win_rate=item.get('winRate', item.get('win_rate', 0)),
                total_trades=item.get('totalTrades', item.get('total_trades', 0)),
                profit=item.get('profitAllTime', item.get('profit', 0)),
            )
        self.stdout.write(self.style.SUCCESS(f'  âœ“ Loaded {len(data)} leaderboard entries'))

