import os
from pathlib import Path

import aiosqlite


def get_db_path() -> str:
    """Return the resolved path to the Peon SQLite database.

    Resolution order:
      1. ``PEON_DB_PATH`` environment variable (always wins).
      2. ``~/.peon/peon_tasks.db``

    The parent directory is created automatically if it doesn't exist.
    """
    env = os.environ.get("PEON_DB_PATH")
    if env:
        p = Path(env).expanduser().resolve()
    else:
        p = Path.home() / ".peon" / "peon_tasks.db"

    p.parent.mkdir(parents=True, exist_ok=True)
    return str(p)


# Kept for backward-compat imports (web.py, etc.) — resolves once at import.
DB_PATH = get_db_path()

SCHEMA = """
CREATE TABLE IF NOT EXISTS projects (
    id TEXT PRIMARY KEY,
    path TEXT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS features (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    project_id TEXT NOT NULL REFERENCES projects(id),
    name TEXT NOT NULL,
    description TEXT NOT NULL DEFAULT '',
    status TEXT NOT NULL DEFAULT 'planned'
        CHECK(status IN ('planned', 'in_progress', 'done', 'cancelled')),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS tasks (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    project_id TEXT NOT NULL REFERENCES projects(id),
    title TEXT NOT NULL,
    description TEXT NOT NULL DEFAULT '',
    priority TEXT NOT NULL DEFAULT 'medium'
        CHECK(priority IN ('low', 'medium', 'high', 'critical')),
    status TEXT NOT NULL DEFAULT 'todo'
        CHECK(status IN ('todo', 'in_progress', 'done', 'cancelled')),
    commit_base TEXT NOT NULL DEFAULT '',
    commit_head TEXT NOT NULL DEFAULT '',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS work_logs (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    task_id INTEGER NOT NULL REFERENCES tasks(id),
    project_id TEXT NOT NULL REFERENCES projects(id),
    summary TEXT NOT NULL,
    files_changed TEXT NOT NULL DEFAULT '',
    test_result TEXT NOT NULL DEFAULT ''
        CHECK(test_result IN ('', 'pass', 'fail', 'skip')),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS loop_heartbeats (
    id TEXT PRIMARY KEY,
    project_id TEXT NOT NULL REFERENCES projects(id),
    pid INTEGER NOT NULL,
    hostname TEXT NOT NULL,
    started_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    last_heartbeat TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
"""


async def init_db(db_path: str | None = None) -> aiosqlite.Connection:
    db = await aiosqlite.connect(db_path or DB_PATH)
    db.row_factory = aiosqlite.Row
    await db.execute("PRAGMA journal_mode=WAL")
    await db.execute("PRAGMA foreign_keys=ON")
    await db.executescript(SCHEMA)
    await db.commit()
    return db


def row_to_dict(row: aiosqlite.Row) -> dict:
    return dict(row)
