"""Seed popular US stocks into the coins table.

Usage:
    python3 scripts/seed_us_stocks.py

Seeds ~20 popular US stocks (NYSE/NASDAQ) as starting data.
Full stock list will be fetched from Yahoo Finance during sync.
"""
from __future__ import annotations

import sys
import os

# Add project root to path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from app import create_app
from app.extensions import db
from app.models.coin import Coin
from app.models.coin_source import CoinSourceMapping

# Popular US stocks to seed (namespaced IDs)
US_STOCKS = [
    # Tech mega-caps (NASDAQ)
    {'id': 'NASDAQ.AAPL', 'symbol': 'AAPL', 'name': 'Apple Inc.', 'sector': 'Technology',
     'sub_sector': 'Consumer Electronics', 'exchange': 'NASDAQ'},
    {'id': 'NASDAQ.MSFT', 'symbol': 'MSFT', 'name': 'Microsoft Corporation', 'sector': 'Technology',
     'sub_sector': 'Software', 'exchange': 'NASDAQ'},
    {'id': 'NASDAQ.GOOGL', 'symbol': 'GOOGL', 'name': 'Alphabet Inc.', 'sector': 'Technology',
     'sub_sector': 'Internet Services', 'exchange': 'NASDAQ'},
    {'id': 'NASDAQ.AMZN', 'symbol': 'AMZN', 'name': 'Amazon.com Inc.', 'sector': 'Consumer Cyclical',
     'sub_sector': 'E-Commerce', 'exchange': 'NASDAQ'},
    {'id': 'NASDAQ.NVDA', 'symbol': 'NVDA', 'name': 'NVIDIA Corporation', 'sector': 'Technology',
     'sub_sector': 'Semiconductors', 'exchange': 'NASDAQ'},
    {'id': 'NASDAQ.META', 'symbol': 'META', 'name': 'Meta Platforms Inc.', 'sector': 'Technology',
     'sub_sector': 'Social Media', 'exchange': 'NASDAQ'},
    {'id': 'NASDAQ.TSLA', 'symbol': 'TSLA', 'name': 'Tesla Inc.', 'sector': 'Consumer Cyclical',
     'sub_sector': 'Electric Vehicles', 'exchange': 'NASDAQ'},
    {'id': 'NASDAQ.AVGO', 'symbol': 'AVGO', 'name': 'Broadcom Inc.', 'sector': 'Technology',
     'sub_sector': 'Semiconductors', 'exchange': 'NASDAQ'},
    {'id': 'NASDAQ.NFLX', 'symbol': 'NFLX', 'name': 'Netflix Inc.', 'sector': 'Communication Services',
     'sub_sector': 'Streaming', 'exchange': 'NASDAQ'},
    {'id': 'NASDAQ.AMD', 'symbol': 'AMD', 'name': 'Advanced Micro Devices', 'sector': 'Technology',
     'sub_sector': 'Semiconductors', 'exchange': 'NASDAQ'},
    # NYSE blue chips
    {'id': 'NYSE.BRK-B', 'symbol': 'BRK-B', 'name': 'Berkshire Hathaway B', 'sector': 'Financial Services',
     'sub_sector': 'Insurance & Diversified', 'exchange': 'NYSE'},
    {'id': 'NYSE.JPM', 'symbol': 'JPM', 'name': 'JPMorgan Chase & Co.', 'sector': 'Financial Services',
     'sub_sector': 'Banking', 'exchange': 'NYSE'},
    {'id': 'NYSE.V', 'symbol': 'V', 'name': 'Visa Inc.', 'sector': 'Financial Services',
     'sub_sector': 'Payment Processing', 'exchange': 'NYSE'},
    {'id': 'NYSE.JNJ', 'symbol': 'JNJ', 'name': 'Johnson & Johnson', 'sector': 'Healthcare',
     'sub_sector': 'Pharmaceuticals', 'exchange': 'NYSE'},
    {'id': 'NYSE.WMT', 'symbol': 'WMT', 'name': 'Walmart Inc.', 'sector': 'Consumer Defensive',
     'sub_sector': 'Retail', 'exchange': 'NYSE'},
    {'id': 'NYSE.UNH', 'symbol': 'UNH', 'name': 'UnitedHealth Group', 'sector': 'Healthcare',
     'sub_sector': 'Health Insurance', 'exchange': 'NYSE'},
    {'id': 'NYSE.XOM', 'symbol': 'XOM', 'name': 'Exxon Mobil Corporation', 'sector': 'Energy',
     'sub_sector': 'Oil & Gas', 'exchange': 'NYSE'},
    {'id': 'NYSE.DIS', 'symbol': 'DIS', 'name': 'The Walt Disney Company', 'sector': 'Communication Services',
     'sub_sector': 'Entertainment', 'exchange': 'NYSE'},
    {'id': 'NYSE.KO', 'symbol': 'KO', 'name': 'The Coca-Cola Company', 'sector': 'Consumer Defensive',
     'sub_sector': 'Beverages', 'exchange': 'NYSE'},
    {'id': 'NYSE.BA', 'symbol': 'BA', 'name': 'The Boeing Company', 'sector': 'Industrials',
     'sub_sector': 'Aerospace & Defense', 'exchange': 'NYSE'},
]


def seed_us_stocks():
    app = create_app()
    with app.app_context():
        from app.helpers.market_db import switch_market_schema
        switch_market_schema('stock_us')

        created = 0
        skipped = 0
        mappings_created = 0

        for stock in US_STOCKS:
            # Check if already exists
            existing = Coin.query.get(stock['id'])
            if existing:
                print(f"  [skip] {stock['id']} — already exists")
                skipped += 1
                continue

            coin = Coin(
                id=stock['id'],
                symbol=stock['symbol'],
                name=stock['name'],
                is_active=True,
                asset_type='stock_us',
                sector=stock['sector'],
                sub_sector=stock.get('sub_sector'),
                lot_size=1,  # US stocks trade in single shares
            )
            db.session.add(coin)
            created += 1
            print(f"  [add]  {stock['id']} — {stock['name']} ({stock['sector']})")

            # Create Yahoo Finance source mapping
            mapping_exists = CoinSourceMapping.query.filter_by(
                coin_id=stock['id'], source='yahoo'
            ).first()
            if not mapping_exists:
                # US stocks use raw ticker on Yahoo Finance (no suffix)
                mapping = CoinSourceMapping(
                    coin_id=stock['id'],
                    source='yahoo',
                    source_coin_id=stock['symbol'],
                    source_url=f"https://finance.yahoo.com/quote/{stock['symbol']}",
                )
                db.session.add(mapping)
                mappings_created += 1

        db.session.commit()
        print(f"\n✓ US Stocks seeded: {created} created, {skipped} skipped, "
              f"{mappings_created} Yahoo mappings created")
        print(f"  Total US stocks in DB: {Coin.query.filter_by(asset_type='stock_us').count()}")


if __name__ == '__main__':
    seed_us_stocks()
