#!/usr/bin/env python3
"""
Gold AutoTrade — One-Click Trial Launcher

This is what trial users run. It:
  1. Auto-detects MT5 installation
  2. Auto-claims a 14-day trial license (no server, no signup)
  3. Starts paper trading engine
  4. Launches the GUI dashboard
  5. Opens the browser to the dashboard

Usage:
  python3 start_trial.py
  python3 start_trial.py --live    (only after onboarding complete)
"""
from __future__ import annotations

import json
import os
import subprocess
import sys
import time
from pathlib import Path

ROOT = Path(__file__).resolve().parent
sys.path.insert(0, str(ROOT))

# ─── ASCII Banner ──────────────────────────────────────────────────

BANNER = r"""
   ____       _     _         _                  _
  / ___| ___ | | __| |       / \   _ __ ___     / \   _ __  _ __
 | |  _ / _ \| |/ _| |_____ / _ \ | '_ ` _ \   / _ \ | '_ \| '_ \
 | |_| | (_) | | |_| |_____/ ___ \| | | | | | / ___ \| |_) | |_) |
  \____|\___/|_|\__|     /_/   \_\_| |_| |_|/_/   \_\ .__/| .__/
                                                     |_|   |_|
"""


def main():
    print(BANNER)
    print("Gold AutoTrade — 14-Day Free Trial")
    print("=" * 55)
    print()

    # ── Step 1: MT5 Detection ──────────────────────────────────────
    print("[1/5] Detecting MT5 installation...")
    mt5_path, mt5_found = _detect_mt5()
    if mt5_found:
        print(f"  ✓ MT5 found: {mt5_path}")
    else:
        print(f"  ⚠ MT5 not auto-detected.")
        print(f"  Expected at: {mt5_path}")
        print(f"  Make sure MT5 is running with the Bridge EA installed.")
    print()

    # ── Step 2: Trial License ──────────────────────────────────────
    print("[2/5] Activating 14-day trial license...")
    try:
        from src.license.trial import claim_trial, get_trial_status
        trial_status = get_trial_status()

        if trial_status["status"] == "TRIAL_ACTIVE":
            print(f"  ✓ Trial active — {trial_status['days_left']} days remaining")
        elif trial_status["status"] == "PAID_LICENSE":
            print(f"  ✓ Paid license active — tier: {trial_status.get('tier', 'pro')}")
        elif trial_status["status"] == "TRIAL_EXPIRED":
            print(f"  ✗ Trial expired. Purchase a license to continue.")
            print(f"    Visit: https://huipin199.com/pricing")
            _wait_and_exit(1)
        else:
            result = claim_trial()
            if result["ok"]:
                print(f"  ✓ Trial activated — {result['days_left']} days remaining")
                print(f"    Expires: {result['expires']}")
            else:
                print(f"  ✗ Cannot activate trial: {result.get('message', 'Unknown error')}")
                _wait_and_exit(1)
    except ImportError as e:
        print(f"  ✗ License module error: {e}")
        _wait_and_exit(1)
    print()

    # ── Step 3: Compliance ─────────────────────────────────────────
    print("[3/5] Risk disclosure...")
    try:
        from src.compliance.disclaimers import has_accepted_risk_disclosure, RISK_DISCLOSURE_V1
        if not has_accepted_risk_disclosure():
            print()
            print(RISK_DISCLOSURE_V1)
            print()
            response = input("I have read and accept the risk disclosure (yes/no): ").strip().lower()
            if response in ("yes", "y"):
                from src.compliance.disclaimers import accept_risk_disclosure
                accept_risk_disclosure()
                print("  ✓ Risk disclosure accepted")
            else:
                print("  ✗ You must accept the risk disclosure to use this software.")
                _wait_and_exit(1)
        else:
            print("  ✓ Risk disclosure previously accepted")
    except ImportError:
        print("  ⚠ Compliance module not available — skipping")
    print()

    # ── Step 4: Start Engine ───────────────────────────────────────
    print("[4/5] Starting paper trading engine...")
    engine_started = False
    try:
        # Check if already running
        pid_file = ROOT / "logs" / "gold_trader.pid"
        if pid_file.exists():
            try:
                pid = int(pid_file.read_text().strip())
                os.kill(pid, 0)
                print(f"  ✓ Engine already running (PID: {pid})")
                engine_started = True
            except (ValueError, OSError):
                pass

        if not engine_started:
            # Start in paper trading mode for trial users
            cmd = [
                sys.executable, str(ROOT / "src" / "pipeline.py"),
                "--source", "mt5",
                "--runtime-intent", "paper_trade",
                "--symbol", "XAUUSD",
                "--timeframe", "M5",
                "--execution-mode", "mock",
                "--poll-seconds", "5",
                "--enable-incident-autofix", "true",
            ]
            _launch_background(cmd, ROOT / "logs" / "engine.log")
            print(f"  ✓ Engine started in paper trading mode")
            print(f"    Logs: logs/engine.log")
    except Exception as e:
        print(f"  ⚠ Could not start engine: {e}")
        print(f"    Start manually: python3 src/pipeline.py --runtime-intent paper_trade ...")
    print()

    # ── Step 5: Launch GUI Dashboard ─────────────────────────────
    print("[5/5] Launching dashboard...")
    gui_url = "http://127.0.0.1:18790"
    try:
        env = os.environ.copy()
        env["GUI_PORT"] = "18790"
        _launch_background(
            [sys.executable, str(ROOT / "gui_backend.py")],
            ROOT / "logs" / "gui_backend.log",
            env=env,
        )
        print(f"  ✓ Dashboard: {gui_url}")
        _open_browser(gui_url)
    except Exception as e:
        print(f"  ⚠ GUI launch issue: {e}")

    # ── Done ───────────────────────────────────────────────────────
    print()
    print("=" * 55)
    print("Trial Ready!")
    print()
    print(f"  Dashboard:     {gui_url}")
    print(f"  View logs:     tail -f logs/engine.log")
    print(f"  GUI logs:      tail -f logs/gui_backend.log")
    print(f"  Add license:   python3 -m src.license.activate --key <key>")
    print()
    print(f"  Trial expires in 14 days. No credit card required.")
    print(f"  Questions? support@huipin199.com")
    print("=" * 55)

    # Keep running
    try:
        while True:
            time.sleep(60)
    except KeyboardInterrupt:
        print("\nShutting down. Thanks for trying Gold AutoTrade!")
        sys.exit(0)


# ─── Helpers ────────────────────────────────────────────────────────

def _detect_mt5() -> tuple[str, bool]:
    """Auto-detect MT5 terminal path."""
    home = Path.home()
    candidates = [
        # macOS (Wine/CrossOver)
        home / "Library" / "Application Support" / "net.metaquotes.wine.metatrader5",
        # Windows
        Path("C:/Program Files/MetaTrader 5"),
        Path("C:/Program Files (x86)/MetaTrader 5"),
        # Custom
        Path(os.environ.get("MT5_PATH", "")),
    ]
    for c in candidates:
        if c.exists():
            return str(c), True
    return str(candidates[0]), False


def _launch_background(cmd: list[str], log_path: Path, env: dict = None) -> None:
    """Launch a subprocess in background, logging to file."""
    log_path.parent.mkdir(parents=True, exist_ok=True)
    with open(log_path, "a") as log:
        subprocess.Popen(
            cmd,
            stdout=log,
            stderr=subprocess.STDOUT,
            start_new_session=True,
            env=env,
        )


def _open_browser(url: str) -> None:
    """Open browser to the given URL."""
    import webbrowser
    import time
    time.sleep(2)
    try:
        webbrowser.open(url)
    except Exception:
        pass


def _wait_and_exit(code: int) -> None:
    print()
    input("Press Enter to exit...")
    sys.exit(code)


if __name__ == "__main__":
    main()
