"""
Legal compliance — risk disclosures, trade confirmations, and regulatory notices.

Integrated into:
  - Startup sequence (first-run acceptance of risk disclosure)
  - Trade execution flow (confirmation dialog before opening positions)
  - GUI (displayed on dashboard and before first trade)
"""
from __future__ import annotations

import json
from datetime import datetime, timezone
from pathlib import Path

DISCLAIMER_FILE = Path(__file__).resolve().parent.parent.parent / "data" / "compliance" / "accepted_disclaimers.json"

RISK_DISCLOSURE_V1 = """
RISK DISCLOSURE AND DISCLAIMER

GOLD AUTOTRADE IS AN AUTOMATED TRADING TOOL. BY USING THIS SOFTWARE, YOU ACKNOWLEDGE:

1. HIGH RISK: Trading gold (XAUUSD) and other financial instruments carries a
   substantial risk of loss. You may lose some or all of your invested capital.

2. NO GUARANTEES: Past performance, backtests, and simulations do not guarantee
   future results. The trading algorithms and AI models may fail under certain
   market conditions.

3. NOT FINANCIAL ADVICE: Gold AutoTrade is a software tool, not a financial
   advisor. All trading decisions are ultimately your responsibility.

4. TECHNICAL RISKS: Software bugs, connectivity issues, broker API failures,
   and market data delays can cause unexpected losses.

5. REGULATORY COMPLIANCE: You are responsible for ensuring your use of this
   software complies with the laws and regulations of your jurisdiction.

6. NO LIABILITY: The developers and distributors of Gold AutoTrade assume no
   liability for any financial losses incurred through the use of this software.

7. DEMO FIRST: You should thoroughly test the software in a demo/paper trading
   environment before using it with real funds.

BY CLICKING "I ACCEPT" OR USING THIS SOFTWARE, YOU CONFIRM THAT YOU HAVE READ,
UNDERSTOOD, AND AGREE TO THESE TERMS. IF YOU DO NOT AGREE, DO NOT USE THIS
SOFTWARE WITH REAL FUNDS.
"""

TRADE_CONFIRMATION_TEMPLATE = """
TRADE CONFIRMATION

You are about to execute a trade with the following details:

  Symbol:     {symbol}
  Action:     {action}
  Volume:     {volume} lots
  Stop Loss:  {sl_price}
  Take Profit: {tp_price}
  Confidence: {confidence}

Estimated risk: ${risk_amount:.2f} ({risk_pct:.1f}% of SL distance)

This action will be executed on your LIVE trading account.
Are you sure you want to proceed?
"""


def _load_accepted() -> dict:
    if DISCLAIMER_FILE.exists():
        try:
            return json.loads(DISCLAIMER_FILE.read_text(encoding="utf-8"))
        except (json.JSONDecodeError, OSError):
            pass
    return {"disclaimers": {}, "trade_confirmations_enabled": True}


def _save_accepted(data: dict) -> None:
    DISCLAIMER_FILE.parent.mkdir(parents=True, exist_ok=True)
    DISCLAIMER_FILE.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")


def has_accepted_risk_disclosure() -> bool:
    """Check if user has accepted the risk disclosure."""
    data = _load_accepted()
    return bool(data.get("disclaimers", {}).get("risk_v1"))


def accept_risk_disclosure() -> None:
    """Record that the user has accepted the risk disclosure."""
    data = _load_accepted()
    data.setdefault("disclaimers", {})
    data["disclaimers"]["risk_v1"] = {
        "accepted_at": datetime.now(timezone.utc).isoformat(),
        "version": "1.0",
    }
    _save_accepted(data)


def is_trade_confirmation_required() -> bool:
    """Check if trade confirmation dialogs are enabled."""
    data = _load_accepted()
    return bool(data.get("trade_confirmations_enabled", True))


def should_block_live_trading() -> bool:
    """Check if live trading should be blocked (no risk disclosure accepted)."""
    return not has_accepted_risk_disclosure()


def format_trade_confirmation(
    symbol: str = "XAUUSD",
    action: str = "BUY",
    volume: float = 0.01,
    sl_price: float = 0,
    tp_price: float = 0,
    confidence: float = 0.8,
    current_price: float = 0,
) -> str:
    """Format a trade confirmation message for display."""
    risk_amount = abs(current_price - sl_price) * volume * 100 if current_price and sl_price else 0
    risk_pct = (abs(current_price - sl_price) / current_price * 100) if current_price else 0

    return TRADE_CONFIRMATION_TEMPLATE.format(
        symbol=symbol,
        action=action,
        volume=volume,
        sl_price=sl_price,
        tp_price=tp_price,
        confidence=f"{confidence:.0%}",
        risk_amount=risk_amount,
        risk_pct=risk_pct,
    )


def get_compliance_status() -> dict:
    """Get overall compliance status for dashboard display."""
    return {
        "risk_disclosure_accepted": has_accepted_risk_disclosure(),
        "trade_confirmations_enabled": is_trade_confirmation_required(),
        "live_trading_blocked": should_block_live_trading(),
    }
