---
phase: 01-foundation
plan: 01
type: execute
wave: 1
depends_on: []
files_modified:
  - possession/db.py
  - possession/schema.sql
  - possession/__init__.py
  - possession/__main__.py
  - pyproject.toml
autonomous: true
requirements:
  - STOR-01
  - STOR-02

must_haves:
  truths:
    - "Running `python -m possession` creates a `possession.db` file at the default path (~/.possession/possession.db)"
    - "Running with `--db /custom/path.db` creates the file at the specified path"
    - "Setting `POSSESSION_DB=/custom/path.db` environment variable uses that path"
    - "All four tables (rooms, containers, items, categories) exist in the created database"
    - "Running twice does not destroy existing data (CREATE TABLE IF NOT EXISTS)"
  artifacts:
    - path: "possession/db.py"
      provides: "DB connection management and path resolution"
      exports: ["get_db_path", "get_connection", "init_db"]
    - path: "possession/schema.sql"
      provides: "SQLite schema for all four entities"
      contains: "CREATE TABLE rooms"
    - path: "possession/__main__.py"
      provides: "CLI entry point with --db flag"
      contains: "argparse"
    - path: "pyproject.toml"
      provides: "Package definition and entry point"
      contains: "[project]"
  key_links:
    - from: "possession/__main__.py"
      to: "possession/db.py"
      via: "calls init_db(path)"
      pattern: "init_db"
    - from: "possession/db.py"
      to: "possession/schema.sql"
      via: "reads and executes schema SQL"
      pattern: "schema\\.sql"
---

<objective>
Bootstrap the Python package, define the SQLite schema for all four entities (rooms, containers, items, categories), and implement DB initialization with configurable path via CLI flag or environment variable.

Purpose: Every Phase 2 and Phase 3 feature depends on a working, schema-initialized database. This is the unconditional foundation.
Output: A pip-installable Python package that, when run, creates a correctly-structured SQLite database at a user-configurable path.
</objective>

<execution_context>
@/Users/paritoshpatil/.claude/get-shit-done/workflows/execute-plan.md
@/Users/paritoshpatil/.claude/get-shit-done/templates/summary.md
</execution_context>

<context>
@.planning/PROJECT.md
@.planning/ROADMAP.md
@.planning/STATE.md
</context>

<tasks>

<task type="auto">
  <name>Task 1: Python package scaffold and pyproject.toml</name>
  <files>
    pyproject.toml
    possession/__init__.py
    possession/__main__.py
  </files>
  <action>
Create a minimal Python package for `possession-terminal`:

1. `pyproject.toml` — use `[build-system]` with `hatchling` or `setuptools`, declare `[project]` with name `possession-terminal`, version `0.1.0`, requires-python `>=3.11`, dependencies `["textual>=0.47.0"]`. Add `[project.scripts]` entry `possession = "possession.__main__:main"`.

2. `possession/__init__.py` — empty or single `__version__ = "0.1.0"` line.

3. `possession/__main__.py` — CLI entry point using `argparse`:
   - Accept `--db PATH` argument (type=str, default=None, help="Path to SQLite database file")
   - Read `POSSESSION_DB` environment variable as fallback (os.environ.get)
   - Call `init_db(path)` from `possession.db` module
   - Print confirmation: `"Database ready: {resolved_path}"`
   - Define `main()` function called by `if __name__ == "__main__": main()`

Do NOT start the Textual app yet — this plan only initializes the DB layer.
  </action>
  <verify>
    <automated>cd /Users/paritoshpatil/Personal/claude-projects/possession-terminal-2 && python -m possession --help 2>&1 | grep -q "\-\-db" && echo "PASS: --db flag exists" || echo "FAIL: missing --db flag"</automated>
    <manual>Check that running `python -m possession` prints "Database ready: ..."</manual>
  </verify>
  <done>`python -m possession --help` shows `--db` option; `python -m possession` runs without error and prints a "Database ready" message</done>
</task>

<task type="auto">
  <name>Task 2: SQLite schema and DB initialization module</name>
  <files>
    possession/schema.sql
    possession/db.py
  </files>
  <action>
Create the SQLite schema and DB management module:

**`possession/schema.sql`** — define all four tables using `CREATE TABLE IF NOT EXISTS`:

```sql
CREATE TABLE IF NOT EXISTS rooms (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL UNIQUE,
    created_at TEXT NOT NULL DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS categories (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL UNIQUE,
    created_at TEXT NOT NULL DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS containers (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    room_id INTEGER NOT NULL REFERENCES rooms(id) ON DELETE CASCADE,
    created_at TEXT NOT NULL DEFAULT (datetime('now')),
    UNIQUE(name, room_id)
);

CREATE TABLE IF NOT EXISTS items (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    description TEXT,
    room_id INTEGER REFERENCES rooms(id) ON DELETE SET NULL,
    container_id INTEGER REFERENCES containers(id) ON DELETE SET NULL,
    category_id INTEGER REFERENCES categories(id) ON DELETE SET NULL,
    purchase_date TEXT,
    cost REAL,
    created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
```

**`possession/db.py`** — implement three public functions:

1. `get_db_path(override: str | None = None) -> Path`:
   - If `override` is given and non-empty → return `Path(override)`
   - Else if `POSSESSION_DB` env var is set → return `Path(os.environ["POSSESSION_DB"])`
   - Else → return `Path.home() / ".possession" / "possession.db"`

2. `get_connection(path: Path) -> sqlite3.Connection`:
   - Create parent directories: `path.parent.mkdir(parents=True, exist_ok=True)`
   - Open connection with `sqlite3.connect(path)`
   - Enable WAL mode: `conn.execute("PRAGMA journal_mode=WAL")`
   - Enable foreign keys: `conn.execute("PRAGMA foreign_keys=ON")`
   - Return the connection

3. `init_db(override: str | None = None) -> Path`:
   - Resolve path via `get_db_path(override)`
   - Open connection via `get_connection(path)`
   - Read `schema.sql` from the same directory as `db.py` using `Path(__file__).parent / "schema.sql"`
   - Execute schema with `conn.executescript(schema_sql)`
   - Commit and close
   - Return the resolved path

Use `importlib.resources` or direct `Path(__file__).parent` to locate `schema.sql` — avoid hardcoded absolute paths.
  </action>
  <verify>
    <automated>cd /Users/paritoshpatil/Personal/claude-projects/possession-terminal-2 && python -c "
from possession.db import init_db
import sqlite3, tempfile, os
with tempfile.NamedTemporaryFile(suffix='.db', delete=False) as f:
    p = f.name
path = init_db(p)
conn = sqlite3.connect(p)
tables = {r[0] for r in conn.execute(\"SELECT name FROM sqlite_master WHERE type='table'\").fetchall()}
conn.close()
os.unlink(p)
assert tables == {'rooms','containers','items','categories'}, f'Missing tables: {tables}'
print('PASS: all 4 tables created')
" 2>&1</automated>
  </verify>
  <done>
    - `init_db(path)` creates a SQLite file at the specified path with all 4 tables (rooms, containers, items, categories)
    - `init_db()` (no args) uses `~/.possession/possession.db` as default
    - Running `init_db` twice does not raise an error or destroy existing data
    - Setting `POSSESSION_DB=/tmp/test.db` overrides the default path
  </done>
</task>

</tasks>

<verification>
Run the full init smoke test:

```bash
cd /Users/paritoshpatil/Personal/claude-projects/possession-terminal-2
# Test 1: default invocation
python -m possession
# Expect: "Database ready: /home/.../.possession/possession.db" or similar

# Test 2: --db flag
python -m possession --db /tmp/poss_test.db
python -c "import sqlite3; c=sqlite3.connect('/tmp/poss_test.db'); print([r[0] for r in c.execute(\"SELECT name FROM sqlite_master WHERE type='table'\")]); c.close()"
# Expect: ['rooms', 'categories', 'containers', 'items'] (order may vary)

# Test 3: env var
POSSESSION_DB=/tmp/poss_env_test.db python -m possession
ls /tmp/poss_env_test.db
# Expect: file exists

# Cleanup
rm -f /tmp/poss_test.db /tmp/poss_env_test.db
```
</verification>

<success_criteria>
- `python -m possession` runs without error and prints a "Database ready: {path}" message
- `python -m possession --db /tmp/x.db` creates `/tmp/x.db` with 4 tables: rooms, containers, items, categories
- `POSSESSION_DB=/tmp/y.db python -m possession` creates `/tmp/y.db`
- Running `init_db` twice is idempotent (no errors, no data loss)
- All table columns match the 7 item fields: name, description, room_id, container_id, category_id, purchase_date, cost
</success_criteria>

<output>
After completion, create `.planning/phases/01-foundation/01-01-SUMMARY.md` documenting:
- Files created and their purpose
- Schema design decisions (ON DELETE CASCADE/SET NULL behavior, UNIQUE constraints)
- Path resolution precedence: --db flag > POSSESSION_DB env var > ~/.possession/possession.db
- Any deviations from this plan
</output>
