from __future__ import annotations

import argparse
import asyncio
from pathlib import Path
import threading
import time

from .client import ERPClient
from .config import load_config
from .db import LocalDB
from .logger import setup_logger
from .sync import StorageAgent
from .tunnel import StorageAgentTunnel
from .updater import AgentUpdater


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description="ERP Local Agent - storage and local ERP tool runtime")
    parser.add_argument("--env", default=None)
    parser.add_argument("--once", action="store_true")
    return parser


def main() -> int:
    args = build_parser().parse_args()
    root = Path.cwd()
    logger = setup_logger(root)
    try:
        config = load_config(args.env)
        db = LocalDB(root / "data" / "agent.db")
        client = ERPClient(config)
        agent = StorageAgent(config, client, db, logger)
        updater = AgentUpdater(config, client, logger, root)
        if args.once:
            updater.maybe_update(force=True)
            agent.run_once()
            return 0
        def update_worker():
            while True:
                updater.maybe_update()
                time.sleep(max(60, config.update_check_interval_seconds))
        threading.Thread(target=update_worker, name="erp-local-agent-updater", daemon=True).start()
        if config.tunnel_enabled:
            asyncio.run(StorageAgentTunnel(agent).run_forever())
        else:
            agent.run_forever()
        return 0
    except KeyboardInterrupt:
        logger.info("ERP Local Agent stopped by user")
        return 0
    except Exception as exc:
        logger.exception("ERP Local Agent failed: %s", exc)
        return 1


if __name__ == "__main__":
    raise SystemExit(main())
