import sys
import os
import traceback
from pathlib import Path

BASE = Path(__file__).parent
LOG = BASE / "startup_error.log"

try:
    venv_site = BASE / "venv" / "lib" / "python3.10" / "site-packages"
    if venv_site.exists():
        sys.path.insert(0, str(venv_site))
    sys.path.insert(0, str(BASE))

    env_file = BASE / ".env"
    if env_file.exists():
        for line in env_file.read_text().splitlines():
            line = line.strip()
            if not line or line.startswith("#") or "=" not in line:
                continue
            k, v = line.split("=", 1)
            os.environ.setdefault(k.strip(), v.strip())

    from app import app as application

except Exception:
    with open(LOG, "w") as f:
        f.write("Python: " + sys.version + "\n")
        f.write("Executable: " + sys.executable + "\n")
        f.write("CWD: " + os.getcwd() + "\n")
        f.write("sys.path:\n")
        for p in sys.path:
            f.write("  " + p + "\n")
        f.write("\n--- Traceback ---\n")
        traceback.print_exc(file=f)
    raise
