"""Configuration loading for project-manager-tui."""

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

try:
  import tomllib
except ModuleNotFoundError:
  import tomli as tomllib


CONFIG_PATH = Path.home() / ".project-manager-tui.toml"


@dataclass
class Config:
  agent_worktree_script: Path
  projects_dir: Path
  projects_filename: str = "Projects.md"
  editor: str = field(default_factory=lambda: os.environ.get("EDITOR", "vim"))
  git_repo_dir: Path = field(default_factory=lambda: Path("."))
  sync_interval: int = 300

  @property
  def projects_file(self) -> Path:
    return self.projects_dir / self.projects_filename


def load_config(config_path: Path | None = None) -> Config:
  """Load config from TOML file."""
  path = config_path or CONFIG_PATH
  if not path.exists():
    print(f"Error: config file not found: {path}")
    print(f"Create {CONFIG_PATH} with at least:")
    print('  agent_worktree_script = "/path/to/agent-worktree.sh"')
    print('  projects_dir = "/path/to/projects"')
    sys.exit(1)

  with open(path, "rb") as f:
    data = tomllib.load(f)

  missing = [k for k in ("agent_worktree_script", "projects_dir") if k not in data]
  if missing:
    print(f"Error: missing required config keys: {', '.join(missing)}")
    sys.exit(1)

  return Config(
      agent_worktree_script=Path(data["agent_worktree_script"]),
      projects_dir=Path(data["projects_dir"]),
      projects_filename=data.get("projects_filename", "Projects.md"),
      editor=data.get("editor", os.environ.get("EDITOR", "vim")),
      git_repo_dir=Path(data.get("git_repo_dir", ".")),
      sync_interval=data.get("sync_interval", 300),
  )
