#!/usr/bin/env python3
"""
bootstrap_vault.py — Obsidian Second Brain Bootstrapper

Creates a complete, production-ready Obsidian vault from scratch.
Generates folder structure, templates, Home dashboard, kanban boards,
and a _CLAUDE.md so Claude can operate the vault from day one.

Usage:
    python bootstrap_vault.py --path ~/my-vault --name "Your Name"
    python bootstrap_vault.py --path ~/my-vault --name "Your Name" --jobs "Acme Corp"

Options:
    --path       Path where the vault should be created (required)
    --name       Your name (required)
    --jobs       Comma-separated list of jobs/companies (default: "Work")
    --no-sidebiz Omit side business module
    --minimal    Create minimal vault (core folders only, no extras)
"""

import argparse
from pathlib import Path
from datetime import date

TODAY = date.today().isoformat()
YEAR = date.today().year


def write(path: Path, content: str):
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(content.strip() + "\n", encoding="utf-8")
    print(f"  ✓ {path}")


def bootstrap(vault: Path, name: str, jobs: list, include_sidebiz: bool):
    primary_job = jobs[0] if jobs else "Work"

    print(f"\n🧠 Bootstrapping vault: {vault}")
    print(f"   Owner: {name}")
    print(f"   Jobs: {', '.join(jobs)}")
    print()

    # ── Folders ──────────────────────────────────────────────────────────────
    folders = [
        "Daily", "Dev Logs", "Tasks", "Projects", "People",
        "Boards", "Knowledge", "Learning", "Ideas", "Content/LinkedIn", "Content/X",
        "Goals", "Health", "Finances/Spending", "Jobs", "Businesses",
        "Mentions", "Reviews", "Life Chapters", "Templates", "_trash",
    ]
    if include_sidebiz:
        folders += ["Side Biz/Deals/Location1", "Side Biz/Deals/Location2"]

    for f in folders:
        (vault / f).mkdir(parents=True, exist_ok=True)

    print("📁 Folders created")

    # ── _CLAUDE.md ────────────────────────────────────────────────────────────
    jobs_table = "\n".join(f"| `Jobs/{j}.md` | Employment / contract role |" for j in jobs)
    write(vault / "_CLAUDE.md", f"""# Claude Operating Manual — {name}'s Vault

> Read this file before doing anything in this vault.
> This is the single source of truth for how Claude operates here.

---

## Vault Identity

- **Owner:** {name}
- **Primary purpose:** Life OS — work, personal, finances
- **Last updated:** {TODAY}

---

## Folder Map

| Folder | Purpose |
|---|---|
| `Daily/` | One note per day. Named `YYYY-MM-DD.md` |
| `Projects/` | Active and archived projects |
| `Tasks/` | Standalone task notes (linked from boards) |
| `Boards/` | Kanban boards |
| `People/` | One note per person |
| `Dev Logs/` | Technical work logs — dated, project-tagged |
| `Knowledge/` | Reference material |
| `Learning/` | Books, courses, content consumed |
| `Content/` | Content calendar and post drafts |
| `Finances/` | Monthly finance notes |
| `Goals/` | Annual and life goals |
| `Mentions/` | Recognition and shoutouts |
| `Jobs/` | Employment and contract roles |
| `Businesses/` | Companies I own |
| `Templates/` | Note templates |
{jobs_table}

---

## Key Files

- **Dashboard:** `Home.md`
- **Work Board:** `Boards/{primary_job}.md`
- **Personal Board:** `Boards/Personal.md`
- **Mentions Log:** `Mentions/Mentions Log.md`

---

## Auto-Save Rules

Claude should auto-save the following **without asking**:
- Decisions made in conversation → relevant project note + daily note
- New people mentioned → People/ (create stub if needed)
- Tasks assigned or committed to → kanban board + Tasks/ note
- Dev work done → Dev Logs/ + project note + daily note
- Mentions/recognition → Mentions Log + person's note + daily note
- Completed tasks → move on kanban to ✅ Done

Claude should **ask before saving**:
- Anything in Finances/ with personal financial data
- Anything involving deleting or archiving an existing note

---

## Naming Conventions

- Daily notes: `YYYY-MM-DD.md`
- Dev logs: `YYYY-MM-DD — Description.md`
- People: Full name (e.g. `Jane Smith.md`)
- Archive prefix: `_archived_`

---

## Kanban Convention

Priority: 🔴 critical · 🟡 important · 🟢 low

Active item:
```
- [ ] 🔴 **Title** · @{{YYYY-MM-DD}}
\tDescription. [[Related Project]] [[Person]]
```

Done item:
```
- [x] ~~🔴 **Title**~~ ✅ Date
```

---

## Propagation Rules

| Event | Also update |
|---|---|
| New project | Board (Backlog) + today's daily note |
| Task done | Board (Done) + project note + daily note |
| Dev session | Dev Logs/ + project note + daily note |
| Person interaction | Daily note + their People/ note |
| Decision made | Project note (Key Decisions) + daily note |
| Mention/recognition | Mentions Log + person's note + daily note |

---

*Generated by obsidian-second-brain bootstrap script.*
*Regenerate: "Claude, update my _CLAUDE.md"*
""")

    # ── Home Dashboard ────────────────────────────────────────────────────────
    write(vault / "Home.md", f"""---
date: {TODAY}
tags:
  - home
aliases:
  - Dashboard
---

# 🧠 {name}'s Life OS

> Claude automatically saves everything important from every conversation.

---

## ⚡ Quick Navigation

| Work | Life | System |
|------|------|--------|
| [[Boards/{primary_job}\\|📋 Work Board]] | [[Goals/{YEAR} Goals\\|🎯 Goals]] | [[Templates/\\|📝 Templates]] |
| [[Boards/Personal\\|📋 Personal]] | [[Finances/Income Streams\\|💵 Income]] | [[Mentions/Mentions Log\\|💬 Mentions]] |
| [[Projects/\\|🔨 Projects]] | [[Health/Health Dashboard\\|🏋️ Health]] | [[People/\\|👥 People]] |

---

## 📅 Recent Daily Notes

```dataview
TABLE WITHOUT ID
  file.link AS "Day",
  mood AS "Mood",
  energy AS "Energy"
FROM "Daily"
SORT date DESC
LIMIT 7
```

---

## 🔥 Active Projects

```dataview
TABLE WITHOUT ID
  file.link AS "Project",
  status AS "Status",
  job AS "Job"
FROM "Projects"
WHERE contains(tags, "project") AND status = "active"
SORT file.name ASC
```

---

## 🎯 Goals

```dataview
TABLE WITHOUT ID
  file.link AS "Goal",
  category AS "Category",
  progress + "%" AS "Progress"
FROM "Goals"
WHERE contains(tags, "goal") AND status = "active"
SORT progress DESC
```

---

## 📊 Vault Stats

```dataviewjs
const all = dv.pages("");
const people = dv.pages('"People"').length;
const projects = dv.pages('"Projects"').length;
const dailies = dv.pages('"Daily"').length;
dv.paragraph(`📝 **${{all.length}}** notes · 👥 **${{people}}** people · 🔨 **${{projects}}** projects · 📅 **${{dailies}}** daily notes`);
```
""")

    # ── Kanban Boards ─────────────────────────────────────────────────────────
    for job in jobs:
        write(vault / f"Boards/{job}.md", f"""---

kanban-plugin: board

---

## 📥 Backlog



## 📋 This Week



## 🔨 In Progress



## ⏳ Waiting On



## 📅 Next Week



## ✅ Done



%% kanban:settings
```
{{"kanban-plugin":"board","list-collapse":[false,false,false,false,false,false]}}
```
%%
""")

    write(vault / "Boards/Personal.md", """---

kanban-plugin: board

---

## 📥 Backlog



## 📋 This Week



## ✅ Done



%% kanban:settings
```
{"kanban-plugin":"board"}
```
%%
""")

    # ── Templates ─────────────────────────────────────────────────────────────
    write(vault / "Templates/Daily Note.md", """---
date: <% tp.date.now("YYYY-MM-DD") %>
tags:
  - daily
mood:
energy:
---

# <% tp.date.now("YYYY-MM-DD") %> — <% tp.date.now("dddd") %>

---

## 🌅 Morning

**Intention:** <% tp.file.cursor() %>

**Grateful for:**
1.
2.
3.

---

## 🎯 Today's Focus

### 🔴 #1 —

### 🟡 #2 —

### 🟢 #3 —

---

## 💼 Work Log



---

## 🏠 Personal



---

## ✅ Habits

- [ ] Exercised
- [ ] Read/learned something
- [ ] Reached out to someone

---

## 🌙 Evening Review

**What went well:**

**What didn't:**

**Tomorrow's #1 priority:**
""")

    write(vault / "Templates/Project.md", """---
date: <% tp.date.now("YYYY-MM-DD") %>
tags:
  - project
status: active
job:
---

# <% tp.file.title %>

## Overview
<% tp.file.cursor() %>

## Architecture


## Key Decisions


## Links


## Related Tasks

```dataview
TABLE WITHOUT ID file.link AS "Task", status AS "Status"
FROM "Tasks"
WHERE contains(file.outlinks, this.file.link)
SORT date DESC
```

## Recent Activity

```dataview
LIST FROM "Daily"
WHERE contains(file.outlinks, this.file.link)
SORT date DESC
LIMIT 5
```
""")

    write(vault / "Templates/Person.md", """---
date: <% tp.date.now("YYYY-MM-DD") %>
tags:
  - person
role:
company:
relationship_strength:
last_interaction: <% tp.date.now("YYYY-MM-DD") %>
follow_up_date:
contact_email:
location:
---

# <% tp.file.title %>

## About
<% tp.file.cursor() %>

## What They Care About


## How We Can Help Each Other


## Notes


---

## Interactions

```dataview
LIST FROM "Daily"
WHERE contains(file.outlinks, this.file.link)
SORT date DESC
LIMIT 15
```
""")

    write(vault / "Templates/Task.md", """---
date: <% tp.date.now("YYYY-MM-DD") %>
tags:
  - task
status: in-progress
project:
job:
requested_by:
due:
---

# <% tp.file.title %>

## Requirements
<% tp.file.cursor() %>

## Implementation Notes


## Delivered

## Related
""")

    write(vault / "Templates/Dev Log.md", """---
date: <% tp.date.now("YYYY-MM-DD") %>
tags:
  - devlog
project:
job:
---

# Dev Log — <% tp.date.now("YYYY-MM-DD") %>

## What I Worked On
<% tp.file.cursor() %>

## Problems Solved


## Decisions Made


## Next Steps
- [ ]
""")

    write(vault / "Templates/Goal.md", f"""---
date: <% tp.date.now("YYYY-MM-DD") %>
tags:
  - goal
category:
status: active
progress: 0
target_date: {YEAR}-12-31
---

# <% tp.file.title %>

## Why This Matters
<% tp.file.cursor() %>

## Success Criteria


## Milestones
- [ ]

## Progress Log
""")

    write(vault / "Templates/Mention.md", """---
date: <% tp.date.now("YYYY-MM-DD") %>
tags:
  - mention
source:
from:
context:
---

# <% tp.file.title %>

## What Was Said
<% tp.file.cursor() %>

## Context


## My Takeaway
""")

    # ── Seed files ────────────────────────────────────────────────────────────
    write(vault / f"Goals/{YEAR} Goals.md", f"""---
date: {TODAY}
tags:
  - goal
---

# {YEAR} Goals

```dataview
TABLE WITHOUT ID file.link AS "Goal", category, progress + "%" AS "Progress", status
FROM "Goals"
WHERE contains(tags, "goal") AND status = "active"
SORT progress DESC
```
""")

    write(vault / "Mentions/Mentions Log.md", f"""---
date: {TODAY}
tags:
  - log
---

# Mentions Log

Every time someone publicly recognizes your work — in Slack, email, meetings, LinkedIn.

```dataview
TABLE WITHOUT ID file.link AS "Mention", date, from, source, context
FROM "Mentions"
WHERE contains(tags, "mention")
SORT date DESC
```
""")

    write(vault / "Health/Health Dashboard.md", f"""---
date: {TODAY}
tags:
  - health
---

# Health Dashboard

## Weekly Habits

```dataview
TABLE WITHOUT ID file.link AS "Day", date AS "Date"
FROM "Daily"
SORT date DESC
LIMIT 14
```

## Notes
""")

    write(vault / "Content/Content Calendar.md", f"""---
date: {TODAY}
tags:
  - content
---

# Content Calendar

```dataview
TABLE WITHOUT ID file.link AS "Post", platform, status, published_date
FROM "Content"
WHERE contains(tags, "content") AND file.name != "Content Calendar"
SORT date DESC
```
""")

    (vault / ".obsidian").mkdir(exist_ok=True)
    write(vault / ".obsidian/app.json", "{}")

    print(f"\n✅ Vault bootstrapped at: {vault}")
    print("\n📋 Recommended Obsidian plugins:")
    print("   • Dataview  — powers the dashboard queries")
    print("   • Templater — powers the Templates/ folder")
    print("   • Kanban    — powers the Boards/ folder")
    print("   • Calendar  — daily note navigation")
    print("\n🤖 Claude MCP config:")
    print(f'   "obsidian-vault": {{"command": "npx", "args": ["-y", "mcp-obsidian", "{vault}"]}}')
    print("\n🧠 _CLAUDE.md is ready — Claude will read it automatically on every session.")


def main():
    parser = argparse.ArgumentParser(description="Bootstrap an Obsidian Second Brain vault")
    parser.add_argument("--path", required=True, help="Path to create the vault")
    parser.add_argument("--name", required=True, help="Your full name")
    parser.add_argument("--jobs", default="Work", help="Comma-separated job/company names")
    parser.add_argument("--no-sidebiz", action="store_true", help="Omit side business module")
    parser.add_argument("--minimal", action="store_true", help="Minimal vault only")
    args = parser.parse_args()

    vault = Path(args.path).expanduser().resolve()
    if vault.exists() and any(vault.iterdir()):
        print(f"⚠️  {vault} already exists and is not empty.")
        confirm = input("Continue anyway? This may overwrite files. [y/N] ").strip().lower()
        if confirm != "y":
            print("Aborted.")
            return

    jobs = [j.strip() for j in args.jobs.split(",")]
    bootstrap(vault, args.name, jobs, include_sidebiz=not args.no_sidebiz)


if __name__ == "__main__":
    main()
