import threading
import os

from .config import RadarConfig
from .api import verify_project
from .watcher import watch_logs
from .structure import push_structure_loop
from .poller import poll_and_send_files


def init_radar(
    project_id: str,
    secret: str,
    service: str = "backend",
    project_root: str | None = None,
    log_file: str | None = None,
):
    """
    Initialize RADAR SDK.
    Starts background services after verifying credentials.
    """

    # Create config object
    config = RadarConfig(
        project_id=project_id,
        secret=secret,
        service=service,
        root=project_root or os.getcwd(),
        log_file=log_file,
    )

    # Validate required fields
    config.validate()

    # Verify credentials with backend
    verify_project(config)

    # Mark as connected
    config.connected = True

    # Start background services
    threading.Thread(
        target=watch_logs,
        args=(config,),
        daemon=True,
    ).start()

    threading.Thread(
        target=push_structure_loop,
        args=(config,),
        daemon=True,
    ).start()

    threading.Thread(
        target=poll_and_send_files,
        args=(config,),
        daemon=True,
    ).start()

    print("🚀 RADAR SDK CONNECTED SUCCESSFULLY")
    print("📂 RADAR watching log file:", config.log_file)
    return config