"""Application configuration."""
import os
from pathlib import Path

# Load .env file if exists (P3: Kimi API config)
# Use stdlib parser to avoid python-dotenv dependency
_env_path = Path(__file__).resolve().parent.parent / ".env"
if _env_path.exists():
    try:
        with open(_env_path, "r", encoding="utf-8") as f:
            for line in f:
                line = line.strip()
                if line and not line.startswith("#") and "=" in line:
                    key, _, value = line.partition("=")
                    key = key.strip()
                    value = value.strip().strip('"').strip("'")
                    if key and key not in os.environ:
                        os.environ[key] = value
    except Exception:
        pass

# Project paths
BACKEND_DIR = Path(__file__).resolve().parent
PROJECT_ROOT = BACKEND_DIR.parent.parent.parent

# Database (SQLite for Phase 2, migrate to PostgreSQL later)
DB_PATH = os.environ.get("AFM_DB_PATH", str(BACKEND_DIR / "afm_sim.db"))
DATABASE_URL = f"sqlite:///{DB_PATH}"

# Server
HOST = os.environ.get("AFM_HOST", "127.0.0.1")
PORT = int(os.environ.get("AFM_PORT", "8000"))

# CORS (allow frontend dev server)
CORS_ORIGINS = os.environ.get(
    "AFM_CORS_ORIGINS",
    "http://localhost:5173,http://127.0.0.1:5173,http://localhost:3000"
).split(",")

# App metadata
APP_NAME = "PCB Axial Flux Motor Simulation System"
APP_VERSION = "1.1.0"
APP_DESCRIPTION = "Web-based simulation plan generation and optimization system for PCB axial flux motors"

# ============================================================
# P3: Kimi AI Configuration
# ============================================================
KIMI_API_KEY = os.environ.get("KIMI_API_KEY", "")
KIMI_BASE_URL = os.environ.get("KIMI_BASE_URL", "https://api.kimi.com/coding/v1")
KIMI_MODEL = os.environ.get("KIMI_MODEL", "k3")
KIMI_MAX_TOKENS = int(os.environ.get("KIMI_MAX_TOKENS", "4096"))
KIMI_TEMPERATURE = float(os.environ.get("KIMI_TEMPERATURE", "1.0"))
KIMI_TIMEOUT = int(os.environ.get("KIMI_TIMEOUT", "120"))
KIMI_MAX_RETRIES = int(os.environ.get("KIMI_MAX_RETRIES", "3"))

# Prompt templates directory
PROMPTS_DIR = BACKEND_DIR / "prompts"

# Schema version (P3: V2 with fidelity/search/calibration fields)
SCHEMA_VERSION = "2.0"
