"""Entry point for the Flet GUI: python -m ai_interview.flet_gui"""

import os
import ssl
from pathlib import Path

import certifi

os.environ.setdefault("SSL_CERT_FILE", certifi.where())
os.environ.setdefault("REQUESTS_CA_BUNDLE", certifi.where())

# Prevent duplicate GUI instances — kill orphaned process from previous session
_PID_FILE = Path.home() / ".ai-interview-gui.pid"

if _PID_FILE.exists():
    try:
        old_pid = int(_PID_FILE.read_text().strip())
        if old_pid != os.getpid():
            os.kill(old_pid, 9)
    except Exception:
        pass
    _PID_FILE.unlink(missing_ok=True)

_PID_FILE.write_text(str(os.getpid()))

from ai_interview.config import load_saved_config
from ai_interview.i18n import set_language
from ai_interview.flet_gui.app import run_flet_gui

_config = load_saved_config()
set_language(_config.get("gui_language", "en"))

# On first run (empty config = v3 fresh start), install LaunchAgent for auto-start
if not _config:
    import shutil
    import subprocess
    import sys
    _plist = Path.home() / "Library" / "LaunchAgents" / "com.ai-interview-assistant.menubar.plist"
    if not _plist.exists():
        _cli = shutil.which("ai-interview") or str(Path(sys.executable).parent / "ai-interview")
        _plist.parent.mkdir(parents=True, exist_ok=True)
        _plist.write_text(f"""\
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
  "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.ai-interview-assistant.menubar</string>
    <key>ProgramArguments</key>
    <array>
        <string>{_cli}</string>
        <string>menubar</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <false/>
</dict>
</plist>""")
        subprocess.run(["launchctl", "load", str(_plist)], capture_output=True)

try:
    run_flet_gui(_config)
finally:
    _PID_FILE.unlink(missing_ok=True)
    os._exit(0)  # Flet threads keep process alive otherwise
