# view_php.py — open your site in Chrome via Selenium using PHP’s built-in server
# Adds ?preview=1 to bypass the "ordered" cookie redirect, and --clear-cookie helper.
# Python 3.8 compatible.

import os, sys, time, socket, subprocess, shutil, argparse
from pathlib import Path
from typing import Optional

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager

def find_free_port(start=5500, tries=200):
    for p in range(start, start + tries):
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            try:
                s.bind(("127.0.0.1", p))
                return p
            except OSError:
                continue
    raise RuntimeError("No free port found")

def wait_port(host, port, timeout=10.0):
    t0 = time.time()
    while time.time() - t0 < timeout:
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.settimeout(0.5)
            try:
                s.connect((host, port))
                return True
            except Exception:
                time.sleep(0.2)
    return False

def resolve_php_exe(cli_php: Optional[str]) -> Optional[str]:
    # 1) explicit flag
    if cli_php and Path(cli_php).exists():
        return cli_php
    # 2) PATH
    exe = shutil.which("php")
    if exe:
        return exe
    # 3) env or common locations (includes Scoop shims)
    candidates = [
        os.environ.get("PHP_EXE"),
        os.path.join(os.environ.get("USERPROFILE", ""), "scoop", "shims", "php.exe"),
        r"C:\Program Files\php\php.exe",
        r"C:\Program Files (x86)\php\php.exe",
        r"C:\xampp\php\php.exe",
        r"C:\laragon\bin\php\php.exe",
        r"C:\wamp64\bin\php\php.exe",
    ]
    for p in candidates:
        if p and Path(p).exists():
            return p
    return None

def launch_php_server(docroot: Path, php_exe: str, port: int) -> subprocess.Popen:
    proc = subprocess.Popen(
        [php_exe, "-S", f"127.0.0.1:{port}", "-t", str(docroot)],
        cwd=str(docroot),
        stdout=subprocess.DEVNULL,
        stderr=subprocess.STDOUT,
    )
    if not wait_port("127.0.0.1", port, 8.0):
        proc.terminate()
        raise RuntimeError("Could not start PHP server (check php.exe and permissions).")
    return proc

def main():
    parser = argparse.ArgumentParser(description="Preview PHP site with Selenium")
    parser.add_argument("entry", nargs="?", default="index.php",
                        help="Entry file to open (default: index.php)")
    parser.add_argument("--php", dest="php_path", default=None,
                        help="Full path to php.exe (overrides auto-detect)")
    parser.add_argument("--clear-cookie", action="store_true",
                        help="Clear the 'ordered' cookie before opening")
    parser.add_argument("--no-preview", action="store_true",
                        help="Do NOT append ?preview=1 to the URL")
    parser.add_argument("--port", type=int, default=0,
                        help="Port to use (default: auto)")
    args = parser.parse_args()

    base = Path.cwd()
    target = base / args.entry
    if not target.exists():
        print(f"[ERR] Entry not found: {target}")
        sys.exit(1)

    php = resolve_php_exe(args.php_path)
    if not php:
        print("[ERR] PHP not found.")
        print("     Quick fix for this session:")
        print('       $env:PATH = "$env:USERPROFILE\\scoop\\shims;$env:PATH"')
        print("       scoop install php")
        print('       $env:PHP_EXE = Join-Path $env:USERPROFILE "scoop\\shims\\php.exe"')
        print("       php -v")
        sys.exit(1)

    port = args.port or find_free_port(5500, 200)
    server = launch_php_server(base, php, port)

    # Build URL (append preview=1 for .php so checkout always shows)
    url = f"http://127.0.0.1:{port}/{target.name}"
    if not args.no_preview and target.suffix.lower() == ".php":
        url += ("&" if "?" in url else "?") + "preview=1"

    print(f"[OK] PHP server → http://127.0.0.1:{port}/")
    print(f"[→ ] Opening: {url}")

    opts = Options()
    opts.add_argument("--start-maximized")
    driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=opts)

    try:
        # Optional: clear cookie via helper endpoint first
        if args.clear_cookie:
            clear_url = f"http://127.0.0.1:{port}/index.php?clear_ordered=1"
            print(f"[• ] Clearing cookie via: {clear_url}")
            driver.get(clear_url)
            time.sleep(0.8)

        driver.get(url)
        print("[INFO] Close the browser to stop.")
        # Keep alive until browser closes
        while True:
            time.sleep(0.5)
            try:
                _ = driver.title
            except Exception:
                break
    finally:
        try: driver.quit()
        except: pass
        try: server.terminate()
        except: pass
        print("[DONE] Stopped.")

if __name__ == "__main__":
    main()
