"""Seed default settings and initial coins for Koinkamu."""
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from dotenv import load_dotenv
load_dotenv()

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

DEFAULT_SETTINGS = [
    {
        'key': 'active_data_source',
        'value': 'indodax',
        'category': 'data_source',
        'description': 'Sumber data aktif (coingecko/indodax)',
    },
    {
        'key': 'sync_timeframes',
        'value': ['1h', '4h', '1D'],
        'category': 'data_source',
        'description': 'Timeframe yang di-sync saat sync coin',
    },
    {
        'key': 'buy_fee_pct',
        'value': 0.31,
        'category': 'fees',
        'description': 'Biaya beli (%) - Ajaib default 0.31%',
    },
    {
        'key': 'sell_fee_pct',
        'value': 0.31,
        'category': 'fees',
        'description': 'Biaya jual (%) - Ajaib default 0.31%',
    },
    {
        'key': 'default_capital',
        'value': 1000000,
        'category': 'capital',
        'description': 'Modal default per koin (IDR)',
    },
    {
        'key': 'active_capital_pct',
        'value': 75,
        'category': 'capital',
        'description': 'Persentase dana aktif untuk trading',
    },
    {
        'key': 'reserve_capital_pct',
        'value': 25,
        'category': 'capital',
        'description': 'Persentase dana cadangan (average down / black swan)',
    },
    # ── Stock (Saham) settings ──
    {
        'key': 'stock_buy_fee_pct',
        'value': 0.15,
        'category': 'fees',
        'description': 'Fee beli saham (%) - Growin default 0.15%',
    },
    {
        'key': 'stock_sell_fee_pct',
        'value': 0.25,
        'category': 'fees',
        'description': 'Fee jual saham (%) - Growin default 0.25%',
    },
    {
        'key': 'stock_sell_tax_pct',
        'value': 0.10,
        'category': 'fees',
        'description': 'PPh Final jual saham (0.10%)',
    },
    {
        'key': 'stock_broker',
        'value': 'growin',
        'category': 'fees',
        'description': 'Broker saham aktif (growin/stockbit/ajaib)',
    },
    {
        'key': 'stock_icon_source',
        'value': 'stockbit',
        'category': 'data_source',
        'description': 'Sumber icon saham (growin/stockbit)',
    },
    {
        'key': 'stock_data_source',
        'value': 'yahoo',
        'category': 'data_source',
        'description': 'Sumber data saham (yahoo)',
    },
    {
        'key': 'stock_sync_timeframes',
        'value': ['1h', '4h', '1D'],
        'category': 'data_source',
        'description': 'Timeframe yang di-sync untuk saham',
    },
    {
        'key': 'stock_us_sync_timeframes',
        'value': ['1h', '4h', '1D'],
        'category': 'data_source',
        'description': 'Timeframe yang di-sync untuk saham US',
    },
]

# Popular coins to pre-seed (namespaced IDs + known source mappings)
INITIAL_COINS = [
    {'id': 'COIN.bitcoin', 'symbol': 'BTC', 'name': 'Bitcoin',
     'sources': {'coingecko': 'bitcoin', 'indodax': 'btcidr'}},
    {'id': 'COIN.ethereum', 'symbol': 'ETH', 'name': 'Ethereum',
     'sources': {'coingecko': 'ethereum', 'indodax': 'ethidr'}},
    {'id': 'COIN.binancecoin', 'symbol': 'BNB', 'name': 'BNB',
     'sources': {'coingecko': 'binancecoin', 'indodax': 'bnbidr'}},
    {'id': 'COIN.ripple', 'symbol': 'XRP', 'name': 'XRP',
     'sources': {'coingecko': 'ripple', 'indodax': 'xrpidr'}},
    {'id': 'COIN.solana', 'symbol': 'SOL', 'name': 'Solana',
     'sources': {'coingecko': 'solana', 'indodax': 'solidr'}},
    {'id': 'COIN.cardano', 'symbol': 'ADA', 'name': 'Cardano',
     'sources': {'coingecko': 'cardano', 'indodax': 'adaidr'}},
    {'id': 'COIN.dogecoin', 'symbol': 'DOGE', 'name': 'Dogecoin',
     'sources': {'coingecko': 'dogecoin', 'indodax': 'dogeidr'}},
    {'id': 'COIN.tron', 'symbol': 'TRX', 'name': 'TRON',
     'sources': {'coingecko': 'tron', 'indodax': 'trxidr'}},
    {'id': 'COIN.polkadot', 'symbol': 'DOT', 'name': 'Polkadot',
     'sources': {'coingecko': 'polkadot', 'indodax': 'dotidr'}},
    {'id': 'COIN.chainlink', 'symbol': 'LINK', 'name': 'Chainlink',
     'sources': {'coingecko': 'chainlink', 'indodax': 'linkidr'}},
    {'id': 'COIN.delorean', 'symbol': 'DMC', 'name': 'DeLorean',
     'sources': {'coingecko': 'delorean'}},
    {'id': 'COIN.moonveil', 'symbol': 'MORE', 'name': 'Moonveil',
     'sources': {'coingecko': 'moonveil'}},
]


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

        print('Creating tables...')
        db.create_all()

        # Seed settings
        print('Seeding default settings...')
        for s in DEFAULT_SETTINGS:
            AppSettings.set(s['key'], s['value'], s['category'], s.get('description'))
        print(f'  -> {len(DEFAULT_SETTINGS)} settings seeded.')

        # Seed coins
        print('Seeding initial coins...')
        count = 0
        for c in INITIAL_COINS:
            existing = db.session.get(Coin, c['id'])
            if not existing:
                coin = Coin(id=c['id'], symbol=c['symbol'], name=c['name'])
                db.session.add(coin)
                count += 1
        db.session.commit()
        print(f'  -> {count} new coins added ({len(INITIAL_COINS) - count} already existed).')

        # Seed source mappings
        print('Seeding coin source mappings...')
        source_count = 0
        source_urls = {
            'coingecko': lambda cid: f'https://www.coingecko.com/id/coins/{cid}',
            'indodax': lambda cid: f'https://indodax.com/market/{cid}',
        }
        for c in INITIAL_COINS:
            for source, source_coin_id in c.get('sources', {}).items():
                existing = CoinSourceMapping.query.filter_by(
                    coin_id=c['id'], source=source
                ).first()
                if not existing:
                    pair = f"{c['symbol']}/IDR" if source == 'indodax' else None
                    url_fn = source_urls.get(source)
                    mapping = CoinSourceMapping(
                        coin_id=c['id'],
                        source=source,
                        source_coin_id=source_coin_id,
                        source_pair=pair,
                        source_url=url_fn(source_coin_id) if url_fn else None,
                        is_available=True,
                    )
                    db.session.add(mapping)
                    source_count += 1
        db.session.commit()
        print(f'  -> {source_count} source mappings added.')

        print('Seed complete!')


if __name__ == '__main__':
    seed()
