using System;
using System.IO;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using PolyTrader.Core.Persistence;
using PolyTrader.Core.Persistence.Ef;
using PolyTrader.Modules.CopyTrading.ConfigImport;
using PolyTrader.Modules.CopyTrading.Persistence;
using PolyTrader.Modules.CopyTrading.Persistence.Ef;

namespace PolyTraderSharp.Services
{
    /// <summary>
    /// Einmalige Config-Migration nach MySQL (Phase 6, Stufe 4).
    /// Quelle: mongoexport-JSON (<see cref="RunFromJson"/>). <see cref="VerifyMySql"/>
    /// liest die migrierte Config zur Kontrolle zurück. Idempotent über Upserts.
    /// </summary>
    public static class ConfigMigrator
    {
        /// <summary>
        /// Config-Migration aus mongoexport-JSON (Ordner mit PolyTraderDB.accounts.json /
        /// .trackers.json) → MySQL. Markets bleiben aussen vor (bereits migriert und werden
        /// vom MarketSync ohnehin laufend aktualisiert). Idempotent via Upserts.
        /// </summary>
        public static void RunFromJson(string folder, string mySqlConnection)
        {
            Console.WriteLine("=== Config-Migration JSON-Export -> MySQL ===");
            Console.WriteLine($"Quelle: {folder}");
            Console.WriteLine($"Ziel   (MySQL): {Redact(mySqlConnection)}");

            var target = new ServiceCollection()
                .AddDbContextFactory<CoreDbContext>(o => o.UseMySql(mySqlConnection, ServerVersion.AutoDetect(mySqlConnection)))
                .AddDbContextFactory<CopyTradingDbContext>(o => o.UseMySql(mySqlConnection, ServerVersion.AutoDetect(mySqlConnection)))
                .BuildServiceProvider();

            var coreFactory = target.GetRequiredService<IDbContextFactory<CoreDbContext>>();
            var ctFactory = target.GetRequiredService<IDbContextFactory<CopyTradingDbContext>>();

            IAccountRepository dstAccounts = new EfAccountRepository(coreFactory);
            ITrackedTraderRepository dstTraders = new EfTrackedTraderRepository(ctFactory);
            ICopyTradingAccountSettingsRepository dstSettings = new EfCopyTradingAccountSettingsRepository(ctFactory);

            // 1) Accounts + Copytrading-Settings (Limit-Felder haengen im Alt-Dokument am Account)
            var accPath = Path.Combine(folder, "PolyTraderDB.accounts.json");
            int accCount = 0, setCount = 0;
            if (File.Exists(accPath))
            {
                foreach (var imp in MongoExportParser.ParseAccounts(File.ReadAllText(accPath)))
                {
                    dstAccounts.Upsert(imp.Account);
                    dstSettings.Upsert(imp.Settings);
                    accCount++;
                    setCount++;
                }
            }
            else
            {
                Console.WriteLine($"[WARN] Nicht gefunden: {accPath}");
            }
            Console.WriteLine($"[OK] Accounts: {accCount} | Copytrading-Settings: {setCount}");

            // 2) Master-Trader
            var trPath = Path.Combine(folder, "PolyTraderDB.trackers.json");
            int trCount = 0;
            if (File.Exists(trPath))
            {
                foreach (var t in MongoExportParser.ParseTraders(File.ReadAllText(trPath)))
                {
                    dstTraders.Upsert(t);
                    trCount++;
                }
            }
            else
            {
                Console.WriteLine($"[WARN] Nicht gefunden: {trPath}");
            }
            Console.WriteLine($"[OK] Master-Trader: {trCount}");
            Console.WriteLine("[INFO] Markets uebersprungen (bereits migriert / MarketSync aktualisiert laufend).");
            Console.WriteLine("=== Migration abgeschlossen ===");
        }

        /// <summary>
        /// Liest die migrierte Config aus MySQL (EF-Repos) zurueck und gibt eine Zusammenfassung
        /// aus. Verifiziert Stufe 5, bevor Mongo entfernt wird.
        /// </summary>
        public static void VerifyMySql(string mySqlConnection)
        {
            Console.WriteLine("=== Verifikation MySQL (EF-Repos) ===");

            var target = new ServiceCollection()
                .AddDbContextFactory<CoreDbContext>(o => o.UseMySql(mySqlConnection, ServerVersion.AutoDetect(mySqlConnection)))
                .AddDbContextFactory<CopyTradingDbContext>(o => o.UseMySql(mySqlConnection, ServerVersion.AutoDetect(mySqlConnection)))
                .BuildServiceProvider();

            var coreFactory = target.GetRequiredService<IDbContextFactory<CoreDbContext>>();
            var ctFactory = target.GetRequiredService<IDbContextFactory<CopyTradingDbContext>>();

            IAccountRepository accRepo = new EfAccountRepository(coreFactory);
            IMarketRepository mktRepo = new EfMarketRepository(coreFactory);
            ITrackedTraderRepository trdRepo = new EfTrackedTraderRepository(ctFactory);
            ICopyTradingAccountSettingsRepository setRepo = new EfCopyTradingAccountSettingsRepository(ctFactory);

            var accounts = accRepo.GetAll();
            Console.WriteLine($"Accounts: {accounts.Count}");
            foreach (var a in accounts.OrderBy(a => a.AccountId))
                Console.WriteLine($"  #{a.AccountId} {a.Name} | Demo={a.IsDemo} Active={a.IsActive} | Wallet={Short(a.WalletAddress)} | Bal={a.TotalBalance}");

            var settings = setRepo.GetAll();
            Console.WriteLine($"Copytrading-Settings: {settings.Count}");
            foreach (var s in settings.OrderBy(s => s.AccountId))
                Console.WriteLine($"  #{s.AccountId} PerMarket={s.PerMarketLimit} PerMaster={s.PerMasterLimit} MaxBuy={s.MaxBuyPrice} PreRedeem={s.PreRedeemLimit}");

            var traders = trdRepo.GetAll();
            Console.WriteLine($"Master-Trader: {traders.Count}");
            int active = traders.Count(t => t.IsActive);
            Console.WriteLine($"  davon aktiv: {active}");
            foreach (var t in traders.OrderBy(t => t.Id).Take(5))
                Console.WriteLine($"  #{t.Id} {t.DisplayName} [{t.Category}] Accounts=[{string.Join(",", t.AssignedAccountIds.OrderBy(x => x))}] Trades={t.TotalTrades}");
            if (traders.Count > 5) Console.WriteLine($"  … (+{traders.Count - 5} weitere)");

            Console.WriteLine($"Markets (aktiv): {mktRepo.GetActive().Count}");
            Console.WriteLine("=== Verifikation abgeschlossen ===");
        }

        private static string Short(string s) =>
            string.IsNullOrEmpty(s) || s.Length <= 12 ? s : $"{s[..6]}…{s[^4..]}";

        private static string Redact(string conn) =>
            System.Text.RegularExpressions.Regex.Replace(conn, "(?i)(password=)[^;]*", "$1***");
    }
}
