#!/usr/bin/env python3
from __future__ import annotations

import argparse
import json
from pathlib import Path


DEFAULT_VAULT = Path.home() / "Documents" / "Agentic-SWMM-Obsidian-Vault"


FILES = {
    ".obsidian/app.json": json.dumps(
        {
            "attachmentFolderPath": "30_Evidence_Layer/Attachments",
            "promptDelete": False,
            "alwaysUpdateLinks": True,
        },
        indent=2,
    )
    + "\n",
    ".obsidian/appearance.json": json.dumps(
        {
            "baseFontSize": 16,
            "translucency": False,
        },
        indent=2,
    )
    + "\n",
    "00_Home/Agentic SWMM Home.md": """---
project: Agentic SWMM
type: vault-home
status: active
---

# Agentic SWMM Home

This vault is the local visualization and review layer for Agentic SWMM. It is designed for a first-time Obsidian user: start here, then follow the links into memory, audit evidence, and skill evolution.

## Start Here

- [[Project Memory]]: stable project memory and evidence boundaries.
- [[Experiment Audit Index]]: generated run-level audit notes.
- [[Claim Register]]: claims, pending claims, and limitations.
- [[Human Review Queue]]: decisions requiring human review.
- [[Skill Proposal Log]]: proposed skill updates derived from audited evidence.

## Layer Model

```text
Execution Layer
  SWMM scripts, MCP tools, runs, QA, plots

Audit Layer
  experiment_provenance.json, comparison.json, experiment_note.md

Memory Layer
  recurring lessons, known boundaries, claim discipline, next actions

Skill Evolution Layer
  proposed skill edits, human review, benchmark verification
```

## Default Audit Destination

```text
~/Documents/Agentic-SWMM-Obsidian-Vault/20_Audit_Layer/Experiment_Audits
```
""",
    "10_Memory_Layer/Project Memory.md": """---
project: Agentic SWMM
type: memory-layer
status: active
---

# Project Memory

This note records stable project memory for local review. It should summarize durable context, not raw chat history.

## System Identity

Agentic SWMM is a reproducible, auditable, agent-coordinated stormwater modeling workflow. Agents may coordinate steps, but deterministic scripts, SWMM outputs, manifests, QA records, and audit artifacts remain the evidence source.

## Working Assumptions

- SWMM computation should remain deterministic and inspectable.
- Agent decisions must be tied to explicit artifacts.
- Missing drainage-network or calibration evidence must be reported as missing, not invented.
- Obsidian is the local visualization and review layer, not the canonical machine-readable source.

## Related Notes

- [[Experiment Audit Index]]
- [[Claim Register]]
- [[Validation Boundaries]]
- [[Skill Proposal Log]]
""",
    "10_Memory_Layer/Claim Register.md": """---
project: Agentic SWMM
type: claim-register
status: active
---

# Claim Register

Use this note to separate evidence-backed claims from ideas, pending claims, and limitations.

## Evidence-Backed Claims

| Claim | Evidence | Status |
|---|---|---|

## Pending Claims

| Claim | Missing Evidence | Next Check |
|---|---|---|

## Limitations

- A minimal real-data smoke test is not a full watershed validation.
- An audit example is evidence-management evidence, not a new hydrologic result.
- Skill updates should require human review and benchmark verification.
""",
    "10_Memory_Layer/Human Review Queue.md": """---
project: Agentic SWMM
type: human-review-queue
status: active
---

# Human Review Queue

This note collects decisions that should be reviewed before becoming claims, documentation, or skill changes.

| Date | Item | Why Review Is Needed | Status |
|---|---|---|---|
""",
    "20_Audit_Layer/Experiment Audit Index.md": """---
project: Agentic SWMM
type: experiment-audit-index
status: active
---

# Experiment Audit Index

This is the main local entry point for run-level audit notes. New audit notes generated by `swmm-experiment-audit` should appear under `20_Audit_Layer/Experiment_Audits` and be indexed here.

## How To Read An Audit

1. Open the Obsidian audit note for the run.
2. Check status, QA gates, metrics, warnings, and comparison results.
3. Open the machine-readable `experiment_provenance.json` for exact commands, repo state, inputs, artifacts, and hashes.
4. Use `comparison.json` when the run is compared against a baseline.
5. Update [[Claim Register]] only when the evidence supports the claim.

## Audited Runs

| Run ID | Status | Audit Note | Provenance JSON | Comparison JSON | Last Updated |
|---|---|---|---|---|---|

## Related Notes

- [[Project Memory]]
- [[Claim Register]]
- [[Validation Boundaries]]
- [[Artifact Map]]
""",
    "30_Evidence_Layer/Artifact Map.md": """---
project: Agentic SWMM
type: artifact-map
status: active
---

# Artifact Map

This note explains where generated evidence lives.

## Repo Run Artifacts

```text
runs/
```

Each audited run should contain:

```text
experiment_provenance.json
comparison.json
experiment_note.md
```
""",
    "30_Evidence_Layer/Validation Boundaries.md": """---
project: Agentic SWMM
type: validation-boundaries
status: active
---

# Validation Boundaries

This note prevents audit evidence from being overstated.

## Supported

- Acceptance runs can support workflow execution and QA claims.
- Audit outputs can support provenance and metric-source claims.
- Real-data minimal runs can support smoke-test claims.

## Not Yet Supported

- Full watershed validation unless complete network, calibration, and observed-flow evidence exist.
- Final calibration performance claims without validation metrics.
- Windows live validation unless tested on Windows.
""",
    "40_Skill_Evolution/Skill Proposal Log.md": """---
project: Agentic SWMM
type: skill-proposal-log
status: active
---

# Skill Proposal Log

This note records proposed skill updates that come from repeated audit findings. A proposal is not accepted until it has human review and benchmark verification.

| Date | Proposed Skill Change | Evidence | Review Status | Verification |
|---|---|---|---|---|
""",
    "90_Templates/Experiment Audit Note Template.md": """---
project: Agentic SWMM
type: template
---

# Experiment Audit - {{run_id}}

## Executive Summary

## Run Identity

## QA Gates

## Key Metrics

## Artifact Index

## Comparison

## Warnings

## Evidence Notes
""",
}


DIRECTORIES = [
    ".obsidian",
    "00_Home",
    "10_Memory_Layer",
    "20_Audit_Layer/Experiment_Audits",
    "30_Evidence_Layer/Attachments",
    "40_Skill_Evolution",
    "90_Templates",
]


def write_if_missing(path: Path, text: str, overwrite: bool) -> bool:
    path.parent.mkdir(parents=True, exist_ok=True)
    if path.exists() and not overwrite:
        return False
    path.write_text(text, encoding="utf-8")
    return True


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description="Initialize the Agentic SWMM Obsidian vault.")
    parser.add_argument(
        "--vault-dir",
        type=Path,
        default=DEFAULT_VAULT,
        help=f"Vault directory to initialize. Defaults to {DEFAULT_VAULT}.",
    )
    parser.add_argument(
        "--overwrite",
        action="store_true",
        help="Overwrite existing template files.",
    )
    return parser.parse_args()


def main() -> None:
    args = parse_args()
    vault = args.vault_dir.expanduser().resolve()

    for directory in DIRECTORIES:
        (vault / directory).mkdir(parents=True, exist_ok=True)

    written = []
    skipped = []
    for relpath, text in FILES.items():
        path = vault / relpath
        if write_if_missing(path, text, args.overwrite):
            written.append(str(path))
        else:
            skipped.append(str(path))

    print(
        json.dumps(
            {
                "ok": True,
                "vault": str(vault),
                "written": written,
                "skipped_existing": skipped,
                "home_note": str(vault / "00_Home" / "Agentic SWMM Home.md"),
                "audit_index": str(vault / "20_Audit_Layer" / "Experiment Audit Index.md"),
            },
            indent=2,
        )
    )


if __name__ == "__main__":
    main()
