"""Parse .nbench.yml project config."""
import os
from pathlib import Path

# Use simple key: value parsing to avoid pyyaml dependency
DEFAULT_CONFIG = {
    "metric": "val_bpb",
    "direction": "minimize",
    "train": "python train.py",
    "results": "results.tsv",
}

def load_config(repo_path="."):
    """Load .nbench.yml from repo root. Returns defaults if not found."""
    config_path = Path(repo_path) / ".nbench.yml"
    config = dict(DEFAULT_CONFIG)
    if config_path.exists():
        with open(config_path) as f:
            for line in f:
                line = line.strip()
                if line and not line.startswith("#") and ":" in line:
                    key, val = line.split(":", 1)
                    config[key.strip()] = val.strip()
    return config

def generate_config(metric="val_bpb", direction="minimize", train_command="python train.py", results_file="results.tsv"):
    """Generate .nbench.yml content."""
    return f"""# Nbench project config
metric: {metric}
direction: {direction}
train: {train_command}
results: {results_file}
"""

def generate_claude_md(project_name, slug, config):
    """Generate CLAUDE.md content for the researcher's repo."""
    return f"""# {project_name}

## Nbench Project

This project is tracked by Nbench. The goal is to {config['direction']} the `{config['metric']}` metric.

### For the researcher (project owner)

Run the watcher to verify incoming contributions:
```
nbench watch --project {slug}
```

This monitors for branches from contributors, tests them in isolated git worktrees,
and auto-merges verified improvements.

To optimise manually, edit the code and run:
```
{config['train']}
```

### For contributors (agents)

To contribute optimisations to this project:

1. Clone this repo
2. Create a branch: `nbench/<your-github-handle>/<short-description>`
3. Edit the code to improve `{config['metric']}`
4. Run `{config['train']}` and verify improvement locally
5. Push your branch
6. Register: `nbench submit --project {slug} --branch <branch-name> --metric <value>`

The researcher's agent will verify your changes in an isolated environment.
If `{config['metric']}` improves, your branch is auto-merged and you earn credits
(1% improvement = 1 credit).

### Config

See `.nbench.yml` for project settings.
"""
