"""
Local dev launcher: admin panel ONLY, without the legacy forwarding Telegram
client (run.py's main-thread `tg_client.loop.run_until_complete(...)`).

Why this exists: `create_client()` builds a TelegramClient from
`telegram.api_id`/`api_hash`/`session_string` settings. If those aren't set (or
the session is stale), `await tg_client.start()` falls back to Telethon's
interactive login prompt (asks for a phone number on stdin) — which hangs
forever in a non-interactive process. The Interactions / Fixed Messages /
Accounts features do NOT depend on that client at all — they use their own
lazily-started runtime (app.core.runtime.TelegramRuntime) — so skipping it
here does not limit testing of those areas.

Usage (from a normal cmd/PowerShell window, no special setup needed):
    venv\\Scripts\\python.exe dev_admin_only.py

Then open http://127.0.0.1:5050 — login: admin / admin123 (or whatever you
already changed it to). Stop it with Ctrl+C.

Runs on port 5050 (not 5000) so it never collides with a real run.py/worker.py
already running.
"""

import sys
import os

try:
    sys.stdout.reconfigure(encoding="utf-8")
    sys.stderr.reconfigure(encoding="utf-8")
except Exception:
    pass

PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
if PROJECT_DIR not in sys.path:
    sys.path.insert(0, PROJECT_DIR)
os.chdir(PROJECT_DIR)


def main():
    from app.core.database import init_db
    init_db()

    from init_app import seed_all
    seed_all()

    from app.core.logger import get_logger, add_db_handler
    add_db_handler()
    logger = get_logger()
    logger.info("[ADMIN-ONLY] Starting (dev, no forwarding Telegram client)...")

    # Same process owns the runtime loop for Interactions/Fixed
    # Messages/Accounts, so their "start" actions run immediately instead of
    # just being persisted for a separate worker process to pick up.
    from app.core.state import mark_engine_process
    mark_engine_process()

    from app.core import audit
    from app.models import audit_log as al
    audit.start_worker()
    audit.record(module=al.MODULE_SYSTEM, action="startup", severity=al.SEV_INFO,
                 message="راه‌اندازی محلی (فقط پنل مدیریت) برای تست")

    try:
        from app.forwarding.service import ForwardTaskService
        resumed = ForwardTaskService().resume_active()
        if resumed:
            logger.info(f"[ADMIN-ONLY] Resumed {resumed} forward task(s)")
    except Exception as exc:
        logger.error(f"[ADMIN-ONLY] Failed to resume forward tasks: {exc}")

    try:
        from app.services.forward_bot_service import resume_pollers
        fb_resumed = resume_pollers()
        if fb_resumed:
            logger.info(f"[ADMIN-ONLY] Started {fb_resumed} forward-approval bot poller(s)")
    except Exception as exc:
        logger.error(f"[ADMIN-ONLY] Failed to start forward-approval bot pollers: {exc}")

    try:
        from app.fixed_messages.service import FixedMessageService
        fm_resumed = FixedMessageService().resume_active()
        if fm_resumed:
            logger.info(f"[ADMIN-ONLY] Resumed {fm_resumed} fixed message(s)")
    except Exception as exc:
        logger.error(f"[ADMIN-ONLY] Failed to resume fixed messages: {exc}")

    try:
        from app.interactions.service import InteractionService
        inter_resumed = InteractionService().resume_active()
        if inter_resumed:
            logger.info(f"[ADMIN-ONLY] Resumed {inter_resumed} interaction(s)")
    except Exception as exc:
        logger.error(f"[ADMIN-ONLY] Failed to resume interactions: {exc}")

    from app.admin.app import create_admin_app

    # Hardcoded (not read from the `system.admin_port` DB setting) so this dev
    # instance never collides with a real run.py/worker.py already using 5000.
    port = 5050
    app = create_admin_app()
    print(f"[ADMIN-ONLY] Panel starting on http://127.0.0.1:{port}")
    app.run(host="127.0.0.1", port=port, use_reloader=False, debug=False, threaded=True)


if __name__ == "__main__":
    main()
