# tools/bootstrap_env.py — Local Virtual Environment Bootstrapper
import os
import sys
import subprocess
import json
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
VENV_DIR = ROOT / ".venv"
EVIDENCE_DIR = ROOT / "Temp" / "evidence" / "WBS-PH1-A"

def log(msg: str):
    print(f"[BOOTSTRAP] {msg}")

def run_cmd(args: list[str]) -> bool:
    try:
        subprocess.run(args, check=True)
        return True
    except subprocess.CalledProcessError as e:
        log(f"Command failed: {args} - Error: {e}")
        return False

def main() -> int:
    log("Initializing local Python environment verification...")

    # 1. Create venv if not exists
    venv_created = False
    if not VENV_DIR.exists():
        log(f"Creating virtual environment in {VENV_DIR}...")
        # Use localized "python" as required by AGENTS.md Windows environment rules
        venv_created = run_cmd([sys.executable, "-m", "venv", str(VENV_DIR)])
    else:
        log("Virtual environment folder '.venv' already exists.")
        venv_created = True

    # Get venv pip and python path
    if os.name == "nt":
        venv_python = VENV_DIR / "Scripts" / "python.exe"
        venv_pip = VENV_DIR / "Scripts" / "pip.exe"
    else:
        venv_python = VENV_DIR / "bin" / "python"
        venv_pip = VENV_DIR / "bin" / "pip"

    # 2. Install core packages
    dependencies_installed = False
    if venv_pip.exists():
        log("Installing core dependencies (PyYAML, openpyxl, yfinance, psycopg[binary], psycopg2-binary, pytest)...")
        # Ensure latest pip and then install dependencies
        run_cmd([str(venv_pip), "install", "--upgrade", "pip"])
        dependencies_installed = run_cmd([str(venv_pip), "install", "PyYAML", "openpyxl", "yfinance", "psycopg[binary]", "psycopg2-binary", "pytest"])
    else:
        log("Error: venv pip.exe not found.")

    # 3. Verify python alignment
    python_version_verified = venv_python.exists()
    if python_version_verified:
        log(f"Python verified successfully: {venv_python}")
    
    # 4. Write evidence JSON
    EVIDENCE_DIR.mkdir(parents=True, exist_ok=True)
    evidence_file = EVIDENCE_DIR / "verdict.json"
    verdict = {
        "venv_created": venv_created,
        "dependencies_installed": dependencies_installed,
        "python_version_verified": python_version_verified
    }
    evidence_file.write_text(json.dumps(verdict, indent=2), encoding="utf-8")
    log(f"Evidence file saved to: {evidence_file}")

    # Success if everything is true
    success = venv_created and dependencies_installed and python_version_verified
    return 0 if success else 1

if __name__ == "__main__":
    sys.exit(main())
