
"""
PKTron Finance — Unified QuantumFinance API
============================================
Single entry-point for all quantum finance algorithms.

Usage
-----
from pktron.finance.api import QuantumFinance

qf = QuantumFinance()
result = qf.qaoa_optimize(returns, covariance)
"""
import numpy as np

from .qaoa_portfolio   import optimize_portfolio
from .vqe_portfolio    import run_vqe_portfolio
from .quantum_monte_carlo import (simulate_returns, estimate_var,
                                  amplitude_estimation, price_european_option)
from .fraud_detection  import build_vqc, train_vqc, predict_transaction
from .grover_search    import build_oracle, run_grover_search
from .qkd_bb84         import generate_key, simulate_channel, detect_eavesdropping


class QuantumFinance:
    """
    Unified Quantum Finance API for PKTron.

    Methods
    -------
    qaoa_optimize(returns, covariance, **kw)
    vqe_optimize(returns, covariance, **kw)
    estimate_risk(mu, sigma, **kw)
    price_option(S0, K, r, sigma, T, **kw)
    train_fraud_detector(data, labels, **kw)
    detect_fraud(transaction, trained)
    search_fraud_patterns(n_qubits, marked_indices, **kw)
    secure_key_exchange(n_bits, eavesdrop, **kw)
    """

    # ── Portfolio ────────────────────────────────────────────────────────

    def qaoa_optimize(self, returns, covariance, p_layers=2,
                      n_restarts=5, risk_penalty=1.0, seed=42):
        """QAOA portfolio optimisation. Returns selection dict."""
        return optimize_portfolio(returns, covariance,
                                  p_layers=p_layers,
                                  n_restarts=n_restarts,
                                  risk_penalty=risk_penalty,
                                  seed=seed)

    def vqe_optimize(self, returns, covariance, depth=2,
                     n_restarts=5, risk_penalty=1.0, seed=7):
        """VQE portfolio optimisation. Returns selection dict."""
        return run_vqe_portfolio(returns, covariance,
                                 depth=depth,
                                 n_restarts=n_restarts,
                                 risk_penalty=risk_penalty,
                                 seed=seed)

    # ── Risk ─────────────────────────────────────────────────────────────

    def estimate_risk(self, mu, sigma, n_scenarios=30_000,
                      horizon_days=252, confidence=0.95, seed=42):
        """
        Simulate returns and compute VaR / CVaR.
        Returns dict with var, cvar, mean_return, std_return, paths.
        """
        sim = simulate_returns(mu, sigma,
                               n_scenarios=n_scenarios,
                               horizon_days=horizon_days,
                               seed=seed)
        var_result = estimate_var(sim['terminal_returns'], confidence)
        return {**sim, **var_result}

    def price_option(self, S0, K, r, sigma, T,
                     option_type='call', n_scenarios=20_000, seed=99):
        """MC option pricing. Returns dict with price, stderr."""
        return price_european_option(S0, K, r, sigma, T,
                                     n_scenarios=n_scenarios,
                                     option_type=option_type,
                                     seed=seed)

    def quantum_amplitude_estimate(self, p_target, n_shots=1024,
                                   n_qpe_qubits=5, seed=0):
        """IQAE amplitude estimation. Returns estimate, error, true_value."""
        return amplitude_estimation(p_target, n_shots=n_shots,
                                    n_qpe_qubits=n_qpe_qubits, seed=seed)

    # ── Fraud ─────────────────────────────────────────────────────────────

    def train_fraud_detector(self, data, labels, depth=2,
                              max_iter=200, seed=0):
        """Train VQC classifier. Returns trained dict for detect_fraud()."""
        return train_vqc(data, labels, depth=depth,
                         max_iter=max_iter, seed=seed)

    def detect_fraud(self, transaction, trained):
        """
        Classify one transaction.
        Returns dict with label, score, fraud_probability, verdict.
        """
        return predict_transaction(transaction, trained)

    def search_fraud_patterns(self, n_qubits, marked_indices,
                               n_iter=None, n_shots=1024, seed=42):
        """
        Grover search for fraudulent patterns in a transaction database.
        Returns found_indices, success_prob, probabilities.
        """
        return run_grover_search(n_qubits, marked_indices,
                                 n_iter=n_iter, n_shots=n_shots, seed=seed)

    # ── Secure Comms ─────────────────────────────────────────────────────

    def secure_key_exchange(self, n_bits=256, eavesdrop=False,
                             intercept_rate=0.5, seed_alice=0, seed_channel=1):
        """
        Full BB84 key exchange simulation.
        Returns dict with secret_key, qber, eve_detected, security_status.
        """
        alice  = generate_key(n_bits=n_bits, seed=seed_alice)
        ch     = simulate_channel(alice, eavesdrop=eavesdrop,
                                  intercept_rate=intercept_rate,
                                  seed=seed_channel)
        result = detect_eavesdropping(ch)
        return result
