"""Ontos default configuration constants.

This file contains the default configuration shipped with Ontos.
DO NOT EDIT THIS FILE - it will be overwritten by ontos_update.py.

To customize settings, override them in ontos_config.py instead.
"""

import os
import importlib.util
from pathlib import Path


def _load_ontology_module():
    """Load ontology module without modifying sys.path (v2.9.6).
    
    v3.0: When bundled in ontos/_scripts/, the path is:
        ontos/_scripts/ontos_config_defaults.py
        -> parent = ontos/_scripts/
        -> parent.parent = ontos/
        -> core/ontology.py = ontos/core/ontology.py
    """
    # From _scripts, go up to ontos/, then into core/ontology.py
    ontology_path = Path(__file__).resolve().parent.parent / "core" / "ontology.py"
    spec = importlib.util.spec_from_file_location("ontos.core.ontology", ontology_path)
    if spec is None or spec.loader is None:
        raise ImportError(f"Cannot load ontology module at {ontology_path}")
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


_ontology = _load_ontology_module()
_TYPE_DEFS = _ontology.TYPE_DEFINITIONS
get_type_hierarchy = _ontology.get_type_hierarchy
get_valid_types = _ontology.get_valid_types
get_valid_type_status = _ontology.get_valid_type_status

# Project root detection
# v3.0: cli.py passes project root via ONTOS_PROJECT_ROOT env var
# This works for both editable and non-editable installs
# Fallback to CWD if not set (cli.py also sets CWD to project root)
PROJECT_ROOT = os.environ.get("ONTOS_PROJECT_ROOT", os.getcwd())


def is_ontos_repo() -> bool:
    """Check if this is the Ontos repository itself (contributor mode).
    
    Returns:
        True if .ontos-internal/ exists (contributor mode),
        False otherwise (user mode).
    """
    return os.path.exists(os.path.join(PROJECT_ROOT, '.ontos-internal'))

# Version - used by update script to check for newer versions
ONTOS_VERSION = "3.0.3"

# GitHub repository for updates
ONTOS_REPO_URL = 'https://github.com/ohjona/project-ontos'
ONTOS_REPO_RAW_URL = 'https://raw.githubusercontent.com/ohjona/project-ontos/main'

# Directory settings (defaults - override in ontos_config.py)
DEFAULT_DOCS_DIR = 'docs'
DEFAULT_LOGS_DIR = 'docs/logs'

# Output files
DEFAULT_CONTEXT_MAP_FILE = 'Ontos_Context_Map.md'
DEFAULT_MIGRATION_PROMPT_FILE = 'migration_prompt.txt'

# Validation thresholds
DEFAULT_MAX_DEPENDENCY_DEPTH = 5

# Document type definitions (v2.9.6: now derived from ontology.py)
# Backward-compatible dict format for existing code
TYPE_DEFINITIONS = {
    name: {
        'rank': td.rank,
        'description': td.description,
        'allows_depends_on': not td.uses_impacts,
    }
    for name, td in _TYPE_DEFS.items()
}

# Valid types for early validation
VALID_TYPES = get_valid_types()

# Derived hierarchy for backward compatibility
TYPE_HIERARCHY = get_type_hierarchy()


# =============================================================================
# EVENT TYPES (v2.0+)
# =============================================================================
# Captures the PRIMARY intent of a development session
# Used in log documents to categorize work

EVENT_TYPES = {
    'feature': {
        'definition': 'Adding new capability to the system',
        'examples': ['Implemented OAuth login', 'Added search functionality'],
    },
    'fix': {
        'definition': 'Correcting broken or incorrect behavior',
        'examples': ['Fixed refresh token bug', 'Resolved race condition'],
    },
    'refactor': {
        'definition': 'Restructuring code without changing behavior',
        'examples': ['Split auth module', 'Migrated to TypeScript'],
    },
    'exploration': {
        'definition': 'Research, spikes, or prototypes',
        'examples': ['Evaluated database options', 'Tested new library'],
    },
    'chore': {
        'definition': 'Maintenance, dependencies, configuration',
        'examples': ['Updated dependencies', 'Fixed CI pipeline'],
    },
    'decision': {  # NEW
        'definition': 'Architectural or design decisions',
        'examples': ['Chose OAuth over SAML', 'Selected PostgreSQL for persistence'],
    },
    'release': {
        'definition': 'Packaging or release activities',
        'examples': ['Published v3.0.0', 'Cut release candidate'],
    },
}

# Valid event type values (for validation)
VALID_EVENT_TYPES = set(EVENT_TYPES.keys())


# =============================================================================
# STATUS VALUES (v2.6+)
# =============================================================================
# Valid status values for document frontmatter

# Valid status values (v2.9: added scaffold, pending_curation for curation levels)
VALID_STATUS = {
    'draft', 'active', 'deprecated', 'archived', 'rejected', 'complete',
    'scaffold',           # Level 0 auto-generated
    'pending_curation',   # Level 1 awaiting full curation
}

# Status descriptions - clarifying archived vs rejected
STATUS_DEFINITIONS = {
    'draft': 'Work in progress (proposals, incomplete docs)',
    'active': 'Current truth (approved, in use)',
    'deprecated': 'Past truth (superseded, kept for reference)',
    'archived': 'Historical record (completed logs moved to archive)',
    'rejected': 'Considered but NOT approved (proposals only - never became truth)',
    'complete': 'Finished work (reviews, completed tasks)',
}

# Valid (type, status) combinations - prevents semantic nonsense
# v2.9.6: Now derived from ontology.py (includes scaffold, pending_curation, auto-generated fixes)
VALID_TYPE_STATUS = get_valid_type_status()

# Stale proposal detection threshold (days)
PROPOSAL_STALE_DAYS = 60

# Minimum characters for rejection reason (prevents useless reasons like "No")
REJECTED_REASON_MIN_LENGTH = 10


# Types that are allowed to be orphans (no dependents)
DEFAULT_ALLOWED_ORPHAN_TYPES = ['product', 'strategy', 'kernel']

# Files/patterns to skip during scanning (defaults)
# - _template.md: Template files
# - Ontos_: Ontos tooling files (Agent Instructions, Manual, Guides, etc.)
DEFAULT_SKIP_PATTERNS = ['_template.md', 'Ontos_', '.ontos-internal/']

# Patterns to skip when scanning docs (v2.3+)
SKIP_PATTERNS = [
    'archive/',
    'Ontos_CHANGELOG.md',
    'README.md',
    '.git/',
    'node_modules/',
    '__pycache__/',
]


# =============================================================================
# WORKFLOW ENFORCEMENT (v2.0+)
# =============================================================================
# These settings control how strictly Ontos enforces workflow rules.
# Override in ontos_config.py to customize for your project.
#
# Strict mode (defaults): Best for teams, ensures context is always captured
# Relaxed mode: Better for solo devs, rapid prototyping, or learning Ontos

# Pre-push hook behavior
# - True (default): BLOCK push until session is archived (recommended for teams)
# - False: Advisory only - show reminder but allow push
ENFORCE_ARCHIVE_BEFORE_PUSH = True

# Session log authorship tracking
# - True (default): --source flag is REQUIRED in ontos_end_session.py
# - False: --source is optional (logs may lack attribution)
REQUIRE_SOURCE_IN_LOGS = True

# =============================================================================
# MEMORY MANAGEMENT (v2.1+)
# =============================================================================
# Controls the "Working Memory" size - how many logs stay in active scanning.
# Logs beyond this threshold should be consolidated and archived.

# Recommended threshold for active logs before consolidation
# - Lower = smaller context maps, more frequent consolidation
# - Higher = more history in context, less consolidation overhead
LOG_RETENTION_COUNT = 15

# =============================================================================
# UX IMPROVEMENTS (v2.3+)
# =============================================================================

# Small change threshold (lines) for pre-push hook
# Changes below this get softer "skip this time" message
SMALL_CHANGE_THRESHOLD = 20

# Default source for session logs (set in ontos_config.py)
# Example: DEFAULT_SOURCE = "Claude Code"
DEFAULT_SOURCE = None

# =============================================================================
# MODE SYSTEM (v2.4+)
# =============================================================================
# Three modes to control workflow friction:
# - "automated": Zero friction, auto-archives on push, best for solo devs
# - "prompted": Blocked until archived, you control details (default for new installs)
# - "advisory": Reminders only, maximum flexibility
#
# Set ONTOS_MODE in ontos_config.py. Individual settings can override mode defaults.

# Current mode (set in ontos_config.py, defaults to None = legacy behavior)
ONTOS_MODE = None

# Mode preset configurations
MODE_PRESETS = {
    'automated': {
        'AUTO_ARCHIVE_ON_PUSH': True,
        'ENFORCE_ARCHIVE_BEFORE_PUSH': False,
        'REQUIRE_SOURCE_IN_LOGS': False,
        'AUTO_CONSOLIDATE': True,
        'AUTO_CONSOLIDATE_ON_COMMIT': True,  # v2.5: Pre-commit hook consolidation
    },
    'prompted': {
        'AUTO_ARCHIVE_ON_PUSH': False,
        'ENFORCE_ARCHIVE_BEFORE_PUSH': True,
        'REQUIRE_SOURCE_IN_LOGS': True,
        'AUTO_CONSOLIDATE': True,
        'AUTO_CONSOLIDATE_ON_COMMIT': False,  # v2.5: Manual consolidation, agent reminder
    },
    'advisory': {
        'AUTO_ARCHIVE_ON_PUSH': False,
        'ENFORCE_ARCHIVE_BEFORE_PUSH': False,
        'REQUIRE_SOURCE_IN_LOGS': False,
        'AUTO_CONSOLIDATE': False,
        'AUTO_CONSOLIDATE_ON_COMMIT': False,  # v2.5: Manual consolidation only
    },
}

# Valid mode values (for validation)
VALID_MODES = set(MODE_PRESETS.keys())

# Auto-archive on push (v2.4+)
# - True: Auto-create session log on git push (automated mode)
# - False: Manual archive required (prompted/advisory modes)
AUTO_ARCHIVE_ON_PUSH = False

# Auto-consolidate in Maintain Ontos (v2.4+)
# - True: Maintenance automatically consolidates old logs
# - False: Manual consolidation only
AUTO_CONSOLIDATE = True

# Auto-consolidate on commit (v2.5+)
# - True: Pre-commit hook consolidates old logs automatically
# - False: Manual consolidation only (or agent reminder in prompted mode)
# Only applies to 'automated' mode by default
AUTO_CONSOLIDATE_ON_COMMIT = False

# Hook timeout to prevent slow hooks from frustrating users (v2.4+)
# Operations in pre-push hook will timeout after this many seconds
HOOK_TIMEOUT_SECONDS = 10

# Consolidation threshold for maintenance (v2.4+)
# Logs older than this many days are candidates for consolidation
CONSOLIDATION_THRESHOLD_DAYS = 30
