"""Daemon configuration."""

import json
import os
from dataclasses import dataclass, field
from pathlib import Path

DEFAULT_PORT = 19777
DEFAULT_INGEST_URL = f"http://localhost:{DEFAULT_PORT}/ingest"


def _default_base_dir() -> Path:
    return Path.home() / ".quickcall-trace"


def _default_ingest_url() -> str:
    return os.environ.get("QC_TRACE_INGEST_URL", DEFAULT_INGEST_URL)


@dataclass
class DaemonConfig:
    """Configuration for the quickcall daemon."""

    # Polling
    poll_interval: float = 5.0  # seconds

    # Paths
    base_dir: Path = field(default_factory=_default_base_dir)

    # Ingest server (override with QC_TRACE_INGEST_URL env var)
    ingest_url: str = field(default_factory=_default_ingest_url)

    # File limits
    max_file_size: int = 100 * 1024 * 1024  # 100MB
    max_retries_per_file: int = 3

    # Retry / pusher
    retry_backoff_base: float = 1.0  # seconds
    retry_backoff_max: float = 60.0  # seconds
    retry_queue_max: int = 10_000  # max messages in retry queue
    retry_timeout: float = 300.0  # 5 min persistent failure threshold

    # Batch size for push
    batch_size: int = 100

    # Organization (set via QC_TRACE_ORG env var or config.json)
    org: str | None = None

    # Source glob patterns (relative to home)
    claude_code_glob: str = ".claude/projects/**/*.jsonl"
    codex_cli_glob: str = ".codex/sessions/*/*/*/rollout-*.jsonl"
    gemini_cli_glob: str = ".gemini/tmp/*/chats/session-*.json"
    cursor_glob: str = ".cursor/projects/*/agent-transcripts/*.txt"

    def __post_init__(self) -> None:
        """Resolve org from env var > config.json > None."""
        if self.org is not None:
            return
        env_org = os.environ.get("QC_TRACE_ORG")
        if env_org:
            self.org = env_org
            return
        config_path = self.base_dir / "config.json"
        if config_path.exists():
            try:
                data = json.loads(config_path.read_text())
                self.org = data.get("org")
            except (json.JSONDecodeError, OSError):
                pass

    @property
    def state_file(self) -> Path:
        return self.base_dir / "state.json"

    @property
    def pid_file(self) -> Path:
        return self.base_dir / "quickcall.pid"
