"""
BizNode Support — Entry Point
===============================
Start the support email system.

Usage:
    python  support/run_support.py          # continuous polling (every 3 min)
    pythonw support/run_support.py          # same, no console window
    python  support/run_support.py --once   # single poll cycle then exit
    python  support/run_support.py --close-stale  # close stale tickets then exit
"""

import argparse
import logging
import os
import signal
import subprocess
import sys
import time
from pathlib import Path

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

_NO_WINDOW = subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0

_SHUTDOWN = False


def _setup_logging():
    log_dir = _PROJECT_ROOT / "logs"
    log_dir.mkdir(exist_ok=True)
    log_file = log_dir / "support.log"

    handlers = [
        logging.FileHandler(str(log_file), encoding="utf-8"),
        logging.StreamHandler(),
    ]

    logging.basicConfig(
        level=logging.INFO,
        format="%(asctime)s [%(name)s] %(levelname)s: %(message)s",
        handlers=handlers,
    )


def _signal_handler(signum, frame):
    global _SHUTDOWN
    _SHUTDOWN = True
    logging.getLogger("biznode.support").info("Shutdown signal received, exiting gracefully...")


def _load_env():
    from support.email_monitor import _load_env as load
    load()


def _ensure_tables():
    from support.ticket_manager import ensure_replies_table
    ensure_replies_table()


def run_once():
    from support.email_monitor import check_inbox
    result = check_inbox(first_run=False)
    log = logging.getLogger("biznode.support")
    if result.get("processed"):
        log.info("Processed %d emails", result["processed"])
    if result.get("error"):
        log.warning("Error: %s", result["error"])
    return result


def run_close_stale():
    from support.ticket_manager import close_stale_tickets
    from support.email_monitor import _send_html_email
    from support.email_templates import auto_close_template

    log = logging.getLogger("biznode.support")
    stale = close_stale_tickets(hours=24)
    for item in stale:
        html = auto_close_template(item["ticket_id"])
        subject = f"[BizNode Support #{item['ticket_id']}] Ticket Closed"
        _send_html_email(item["email"], subject, html)
        log.info("Auto-closed %s (%s)", item["ticket_id"], item["email"])
    return stale


def run_poll_loop():
    from support.email_monitor import check_inbox

    log = logging.getLogger("biznode.support")
    poll_interval = 180  # 3 minutes
    stale_interval = 3600  # 1 hour
    last_stale_check = 0

    is_first = True
    log.info("Support email monitor started — polling every %ds", poll_interval)

    while not _SHUTDOWN:
        try:
            result = check_inbox(first_run=is_first)
            is_first = False
            if result.get("processed"):
                log.info("Processed %d emails", result["processed"])
            if result.get("error"):
                log.warning("Inbox check error: %s", result["error"])
        except Exception as exc:
            log.error("Poll loop error: %s", exc)

        now = time.time()
        if now - last_stale_check >= stale_interval:
            try:
                run_close_stale()
                last_stale_check = now
            except Exception as exc:
                log.error("Stale ticket check error: %s", exc)

        for _ in range(poll_interval):
            if _SHUTDOWN:
                break
            time.sleep(1)

    log.info("Support email monitor stopped.")


def main():
    parser = argparse.ArgumentParser(description="BizNode Support Email System")
    parser.add_argument("--once", action="store_true", help="Single poll cycle then exit")
    parser.add_argument("--close-stale", action="store_true", help="Close stale tickets then exit")
    args = parser.parse_args()

    _setup_logging()
    _load_env()
    _ensure_tables()

    signal.signal(signal.SIGINT, _signal_handler)
    signal.signal(signal.SIGTERM, _signal_handler)

    if args.once:
        run_once()
    elif args.close_stale:
        run_close_stale()
    else:
        run_poll_loop()


if __name__ == "__main__":
    main()
