"""
South Star OS Daemon
Runs as a background service on the customer's server.
Collects system metrics, receives SDK traces, sanitizes everything, ships to South Star.
"""
import json
import logging
import os
import sys
import time
from pathlib import Path

from daemon import receiver, sanitizer, shipper
from daemon.collectors import system

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s [southstar-daemon] %(levelname)s %(message)s',
    datefmt='%Y-%m-%dT%H:%M:%S',
)
logger = logging.getLogger(__name__)

CONFIG_PATH = Path(os.environ.get('SOUTHSTAR_CONFIG', '/etc/southstar/config.json'))
DAEMON_VERSION = '0.1.0'
DEFAULT_API_URL = 'https://southstar.app/api/v1/ingest'
MIN_INTERVAL = 10
MAX_INTERVAL = 3600


def _parse_interval() -> int:
    raw = os.environ.get('SOUTHSTAR_INTERVAL', '60')
    try:
        val = int(raw)
    except (ValueError, TypeError):
        logger.warning('Invalid SOUTHSTAR_INTERVAL %r, using default 60s.', raw)
        return 60
    if val < MIN_INTERVAL or val > MAX_INTERVAL:
        logger.warning('SOUTHSTAR_INTERVAL %d out of range [%d, %d], clamping.', val, MIN_INTERVAL, MAX_INTERVAL)
        return max(MIN_INTERVAL, min(MAX_INTERVAL, val))
    return val


def load_config() -> dict:
    if not CONFIG_PATH.exists():
        logger.error('Config not found at %s. Run the installer first.', CONFIG_PATH)
        sys.exit(1)
    with CONFIG_PATH.open() as f:
        config = json.load(f)

    if not config.get('api_key'):
        logger.error('Config at %s is missing "api_key".', CONFIG_PATH)
        sys.exit(1)

    api_url = config.get('api_url', DEFAULT_API_URL).rstrip('/')
    if not api_url.startswith('https://'):
        logger.error('api_url must use HTTPS. Got: %s', api_url)
        sys.exit(1)
    config['api_url'] = api_url

    return config


def run():
    config = load_config()
    api_key = config['api_key']
    service_name = config.get('service_name', 'server')
    environment = config.get('environment', 'production')
    api_url = config['api_url']
    collect_interval = _parse_interval()

    logger.info('Starting South Star daemon v%s for service "%s"', DAEMON_VERSION, service_name)
    logger.info('Shipping to %s every %ds', api_url, collect_interval)

    # Start local receiver for SDK traces
    receiver.start(host='localhost', port=9999)

    # Send first heartbeat immediately so dashboard shows "Connected"
    try:
        metrics = system.collect()
        shipper.ship_heartbeat(api_key, service_name, environment, metrics, api_url, DAEMON_VERSION)
        logger.info('First heartbeat sent.')
    except Exception as exc:
        logger.warning('First heartbeat failed (will retry next cycle): %s', exc)

    while True:
        time.sleep(collect_interval)

        # System metrics
        try:
            metrics = system.collect()
            shipper.ship_heartbeat(api_key, service_name, environment, metrics, api_url, DAEMON_VERSION)
        except Exception as exc:
            logger.warning('Failed to collect/ship metrics: %s', exc)

        # SDK traces
        try:
            raw_spans = receiver.drain()
            if raw_spans:
                clean_spans = [sanitizer.sanitize_span(s) for s in raw_spans]
                shipper.ship_traces(api_key, clean_spans, api_url)
                logger.debug('Shipped %d SDK spans.', len(clean_spans))
        except Exception as exc:
            logger.warning('Failed to ship SDK spans: %s', exc)


if __name__ == '__main__':
    run()
