PT Coach PT Coach Blueprint
Open Blueprint Android Health Connect Supabase Edge 7/24 EVREN Qwen3.8 Telegram Webhook

Saatten Telemetri Oku, Bulutta Düşün, Telegram'da Eğit.

Read Telemetry from the Watch, Think in the Cloud, Coach on Telegram.

Akıllı saat ve bantlardan gelen uyku evreleri, adımlar ve Strava antrenmanlarını Android Health Connect üzerinden cihazda toplayan; Supabase Postgres & Edge Functions ile 7/24 bulutta işleyen ve EVREN LLM API ile sesli/yazılı kişisel antrenörlük sunan açık kaynaklı tam yığın sistem mimarisi.

An open, full-stack architecture that collects sleep stages, steps and Strava workouts from smartwatches and bands on the device via Android Health Connect, processes them in the cloud 24/7 with Supabase Postgres & Edge Functions, and delivers voice and text personal coaching through the EVREN LLM API.

Sıfır Bulut Bağımlılığı (Cihaz İçi)No Vendor Cloud (On-Device) Veriler üçüncü taraf bulut API'lerinden değil; telefondaki Health Connect yerel şifreli deposundan okunur. Data is read from Health Connect's local encrypted store on the phone, not from third-party cloud APIs.
7/24 Kesintisiz KoçlukRound-the-Clock Coaching Bilgisayar kapalıyken bile Supabase Edge Functions ve pg_cron zamanlayıcılarıyla gün boyu tetiklenir. Supabase Edge Functions and pg_cron schedules trigger it all day, even with your computer switched off.
Çok Modlu (Multimodal) ZekaMultimodal Intelligence Metin, sesli mesaj (Qwen3-ASR), sesli yanıt (VoxCPM2) ve tabak fotoğrafından kalori/protein çıkarma. Text, voice notes (Qwen3-ASR), spoken replies (VoxCPM2) and calorie/protein estimates from a plate photo.
ISSN & ACSM Bilimsel TemelGrounded in ISSN & ACSM Mifflin-St Jeor metabolizma hesabı, hedefe göre protein (1.8-2.0 g/kg) ve ACWR sakatlık önleme oranı. Mifflin-St Jeor metabolic rate, goal-based protein (1.8-2.0 g/kg) and the ACWR injury-prevention ratio.
BCR PT Coach ● 7/24 Çevrim içi (Supabase Bulut)● Online 24/7 (Supabase Cloud)
⚡ Gerçek sistem akışı simülasyonu. Gizlilik gereği kişisel veriler maskelenmiştir.⚡ A simulation of the real system flow. Personal data is masked for privacy.
Veri HattıData Pipeline

Sensörden Telegram'a: Veri Nasıl Akar?

From Sensor to Telegram: How the Data Flows

Tescilli üçüncü taraf bulutlara kilitlenmeden, cihaz içi Health Connect ile kurulan güvenli veri hattı.

A secure pipeline built on on-device Health Connect, without lock-in to proprietary third-party clouds.

01 · BİLEKTEKİ SENSÖR01 · SENSOR ON THE WRIST

Giyilebilir CihazlarWearables

Xiaomi Watch, Strava, Garmin veya Samsung Health, kalp atım hızı, adım ve uyku seanslarını üretir.

Xiaomi Watch, Strava, Garmin or Samsung Health produce heart rate, steps and sleep sessions.

02 · CİHAZ İÇİ DEPO02 · ON-DEVICE STORE

Health Connect

Android'in yerel şifreli sağlık veritabanı. Cihaz dışına veri çıkmaz, her sensör türü ayrı izinle korunur.

Android's local, encrypted health database. Data stays on the device and each data type sits behind its own permission.

03 · KOTLIN KÖPRÜSÜ03 · KOTLIN BRIDGE

Android Bridge App

Arka plan WorkManager ile 15 dakikada bir çalışır; uyku evrelerini ve adımları toplayıp Supabase'e REST ile iletir.

Runs every 15 minutes via background WorkManager, collecting sleep stages and steps and sending them to Supabase over REST.

04 · 7/24 BULUT04 · 24/7 CLOUD

Supabase Engine

Postgres üzerinde RLS ile saklanır; pg_cron zamanlayıcıları sabah ve öğün atlama uyarılarını yönetir.

Stored in Postgres behind RLS; pg_cron schedules handle the morning briefing and skipped-meal nudges.

05 · YZ AKLI05 · AI BRAIN

EVREN LLM & Telegram

Qwen3.8-Flash-Next modeli 10 araçla veriyi yorumlar, ses kaydını dinler ve Telegram Webhook üzerinden yanıtlar.

The Qwen3.8-Flash-Next model interprets the data with 10 tools, listens to voice notes and replies through a Telegram webhook.

Yerel Android UygulamasıNative Android App

Android Health Connect Köprüsü Nasıl Çalışır?

How the Android Health Connect Bridge Works

com.ptcoach.bridge paketinin arka planda telemetriyi okuma ve buluta güvenli aktarma mantığı.

How the com.ptcoach.bridge package reads telemetry in the background and ships it securely to the cloud.

Cihaz İçi İzinler ve Veri TürleriOn-Device Permissions and Data Types

Android 14+ ile sistemin çekirdeğine dahil edilen Health Connect API kullanılır. Uygulama yalnızca okuma yetkisi talep eder:

It uses the Health Connect API, built into the OS since Android 14. The app only requests read access:

  • SleepSessionRecord: Başlangıç/bitiş zamanı ve evreler (Uyanık, Hafif, Derin, REM).
  • StepsRecord: Günlük periyotlarla toplanan adım toplamları (AggregateGroupByPeriod).
  • HeartRateRecord: Dinlenik ve ortalama gün içi nabız verisi.
  • ExerciseSessionRecord: Strava veya saatten gelen seans türü, süre ve rota bilgisi.
  • SleepSessionRecord: start/end time and stages (Awake, Light, Deep, REM).
  • StepsRecord: step totals aggregated per day (AggregateGroupByPeriod).
  • HeartRateRecord: resting and average daytime heart rate.
  • ExerciseSessionRecord: session type, duration and route from Strava or the watch.

Xiaomi Mi Fitness gibi üreticilerin yazdığı çift/çakışan kayıtlar için süresi en uzun olan kaydı seçen akıllı tekilleştirme (deduplication) algoritması barındırır.

Includes a deduplication step that keeps the longest record when vendors such as Xiaomi Mi Fitness write duplicate or overlapping entries.

// Kotlin: HealthSync.kt - Veri Okuma ve Senkronizasyon
suspend fun syncHealthData(context: Context) = withContext(Dispatchers.IO) {
    val client = HealthConnectClient.getOrCreate(context)
    val startTime = Instant.now().minus(Duration.ofDays(7))
    val endTime = Instant.now()

    // 1. Günlük Adımları Dilimleyerek Topla
    val stepsRequest = AggregateGroupByPeriodRequest(
        metrics = setOf(StepsRecord.COUNT_TOTAL),
        timeRangeFilter = TimeRangeFilter.between(startTime, endTime),
        timeRangeSlicer = Period.ofDays(1)
    )
    val steps = client.aggregateGroupByPeriod(stepsRequest)

    // 2. Uyku Evrelerini (Derin/REM/Uyanık) Oku
    val sleepRecords = client.readRecords(
        ReadRecordsRequest(
            recordType = SleepSessionRecord::class,
            timeRangeFilter = TimeRangeFilter.between(startTime, endTime)
        )
    ).records

    // 3. Supabase Edge Ingestion Endpoint'ine İlet
    postPayloadToSupabase(steps, sleepRecords)
}
// Kotlin: HealthSync.kt - Read and Sync
suspend fun syncHealthData(context: Context) = withContext(Dispatchers.IO) {
    val client = HealthConnectClient.getOrCreate(context)
    val startTime = Instant.now().minus(Duration.ofDays(7))
    val endTime = Instant.now()

    // 1. Aggregate daily steps
    val stepsRequest = AggregateGroupByPeriodRequest(
        metrics = setOf(StepsRecord.COUNT_TOTAL),
        timeRangeFilter = TimeRangeFilter.between(startTime, endTime),
        timeRangeSlicer = Period.ofDays(1)
    )
    val steps = client.aggregateGroupByPeriod(stepsRequest)

    // 2. Read sleep stages (Deep/REM/Awake)
    val sleepRecords = client.readRecords(
        ReadRecordsRequest(
            recordType = SleepSessionRecord::class,
            timeRangeFilter = TimeRangeFilter.between(startTime, endTime)
        )
    ).records

    // 3. Send to the Supabase Edge ingestion endpoint
    postPayloadToSupabase(steps, sleepRecords)
}
Sistem KatmanlarıSystem Layers

Etkileşimli Mimari İncelemesi

Interactive Architecture Walkthrough

Her katmanın üstüne tıklayarak görevlerini ve dosya bağlantılarını inceleyin.

Click any module to see what it does and where it lives in the code.

Mobil & Sensör KatmanıMobile & Sensor Layer
7/24 Bulut & Veritabanı24/7 Cloud & Database
Yapay Zeka & Çok Modlu ZekaAI & Multimodal Intelligence
Fonksiyon ÇağrılarıFunction Calls

Modelin Kullandığı 12 Çekirdek Araç

The 12 Core Tools the Model Uses

LLM'in halüsinasyon görmeden doğrudan doğrulanmış veritabanı kayıtlarıyla konuşmasını sağlayan araç seti.

A toolset that keeps the LLM grounded in verified database records instead of guessing.

Araç AdıTool Tetiklenme AmacıTriggered By Veri KaynağıData Source Çıktı & EtkiOutput & Effect
Bilimsel TemelScientific Basis

Koçun Karar Algoritması Neye Dayanır?

What the Coach's Decisions Are Based On

Spor bilimleri ve beslenme literatüründen (ISSN, ACSM, PubMed) alınan değişmez kurallar.

Fixed rules taken from the sports science and nutrition literature (ISSN, ACSM, PubMed).

1. Mifflin-St Jeor & TDEE Hesabı1. Mifflin-St Jeor & TDEE

Bazal Metabolizma Hızı (BMR): 10×Kilo + 6.25×Boy - 5×Yaş + 5. Sağlıklı yağ yakımı için TDEE'nin %15-20 altı (~400-450 kcal açık) hedeflenir.

Basal Metabolic Rate (BMR): 10×Weight + 6.25×Height - 5×Age + 5. For healthy fat loss it targets 15-20% below TDEE (a ~400-450 kcal deficit).

2. Kas Kütlesi Koruma (ISSN)2. Preserving Muscle Mass (ISSN)

Kalori açığında kas kaybını engellemek için hedef kilo başına 1.8–2.0 g/kg protein. Öğün başına 25–40g lösin içeriği yüksek protein dağılımı.

1.8–2.0 g/kg of target body weight in protein to prevent muscle loss in a deficit, spread as 25–40 g of leucine-rich protein per meal.

3. ACWR Yük Takibi (Gabbett Kuralı)3. ACWR Load Tracking (Gabbett)

Son 7 günün antrenman yükü (akut) ile son 28 günün ortalaması (kronik) karşılaştırılır. 0.8–1.3 arası güvenli gelişim, 1.5+ sakatlık alarmıdır.

Compares the last 7 days of training load (acute) with the 28-day average (chronic). 0.8–1.3 is safe progress; 1.5+ is an injury warning.

4. Uyku Mimarisi ve Ghrelin Kontrolü4. Sleep Architecture and Ghrelin

Net 7 saat altı uyku ghrelin (açlık) hormonunu artırır. Derin uyku kas tamirini (%15-25), REM zihinsel toparlanmayı (%20-25) sağlar.

Less than 7 hours of net sleep raises ghrelin (the hunger hormone). Deep sleep (15-25%) drives muscle repair; REM (20-25%) drives mental recovery.

Bilgi BankasıKnowledge Base

Koç Neyi, Hangi Kaynağa Dayanarak Söylüyor?

What the Coach Says, and Which Source Backs It

Botun bilgi bankası üç kısa protokol dosyası ve aşağıdaki bilimsel kaynaklardan oluşur. Hepsi NotebookLM'e yüklenip tek bir not defterinde toplanır; search_knowledge_base aracı cevap verirken bu kaynaklara işaret eder.

The bot's knowledge base is three short protocol files plus the scientific sources below. They all go into a single NotebookLM notebook, and the search_knowledge_base tool points back to them when it answers.

Günlük Hazırlık Karar Ağacı (Uyku + HRV + Nabız)Daily Readiness Decision Tree (Sleep + HRV + Resting HR)

Tek günlük mutlak HRV değerine değil, kişinin kendi 30 günlük bazalinden yüzde sapmasına bakılır. Sabah brifingi bu tabloya göre şekillenir.

It looks at the percentage deviation from the person's own 30-day baseline, not at a single day's absolute HRV. The morning briefing follows this table.

SinyalSignal KriterCriteria O günün kararıDecision for the day
Yeşil · HazırGreen · Ready Net uyku ≥ 6.5 sa, HRV bazale yakın (> −%5), dinlenik nabız normal (< +3 bpm)Net sleep ≥ 6.5 h, HRV near baseline (> −5%), resting HR normal (< +3 bpm) Planlanan ana antrenman tam kapasite. Normal kalori açığı korunur.Planned main session at full capacity. Normal calorie deficit stays.
Sarı · DikkatliAmber · Caution Net uyku 5.5–6.5 sa VEYA HRV bazalden %5–12 düşük VEYA nabız +3–4 bpmNet sleep 5.5–6.5 h OR HRV 5–12% below baseline OR resting HR +3–4 bpm Yüksek yoğunluk yerine 30–45 dk Zone 2 veya hacmi %15–20 düşürülmüş teknik antrenman.Swap high intensity for 30–45 min of Zone 2, or a technique session with 15–20% less volume.
Kırmızı · ToparlanmaRed · Recover Net uyku < 5.5 sa VEYA HRV bazalden %12'den fazla düşük VEYA nabız ≥ +5 bpmNet sleep < 5.5 h OR HRV more than 12% below baseline OR resting HR ≥ +5 bpm Ağır antrenman iptal; 20–30 dk hafif yürüyüş + mobilite. Kalori açığı o gün zorlanmaz, protein ve su yüksek tutulur.Hard session cancelled; 20–30 min easy walk + mobility. No pushing the deficit that day; protein and fluids stay high.
KodCode KaynakSource Bot ne için kullanıyorWhat the bot uses it for
ISSN-DIETISSN Position Stand: Diets and Body CompositionAragon et al. · JISSN 2017Kalori açığında kas koruma, 1.6–2.4 g/kg proteinPreserving muscle in a deficit, 1.6–2.4 g/kg protein
ISSN-PROTEINISSN Position Stand: Protein and ExerciseJäger et al. · JISSN 2017Öğün başına 20–40 g protein, lösin eşiği20–40 g protein per meal, leucine threshold
ACSMACSM Physical Activity GuidelinesAmerican College of Sports MedicineHaftalık 150+ dk kardiyo, 2–3 gün kuvvet150+ min cardio a week, 2–3 strength days
MIFFLIN-BMRA new predictive equation for resting energy expenditureMifflin et al. · Am J Clin Nutr 1990BMR ve TDEE hesabıBMR and TDEE calculation
ACWR-LOADThe training-injury prevention paradoxGabbett · Br J Sports Med 2016Akut:kronik yük oranı, 0.8–1.3 güvenli bölgeAcute:chronic workload ratio, 0.8–1.3 safe zone
HRV-TRAININGHRV-guided endurance training: a SWOT analysis for load management2026HRV ile günlük antrenman şiddeti ayarıAdjusting daily training intensity with HRV
HRV-MOBILEMonitoring training adaptation and recovery using HRV via mobile devicesNarrative review · 2025Saat ve telefonla ölçülen HRV'nin güvenilirliğiHow reliable watch- and phone-based HRV is
SLEEP-ATHLETESleep and the athlete: 2021 expert consensus recommendationsWalsh et al. · Br J Sports MedUyku süresi hedefleri ve performansSleep duration targets and performance
SLEEP-MUSCLESleep and muscle recovery: endocrinological and molecular basisDattilo et al. · Med Hypotheses 2011Derin uyku, büyüme hormonu ve kas onarımıDeep sleep, growth hormone and muscle repair
SLEEP-APPETITESleep curtailment, leptin, ghrelin and appetiteSpiegel et al. · Ann Intern Med 2004Kısa uykunun ertesi gün iştaha etkisiHow short sleep drives next-day appetite

⚠️ Bu sayfa bir yazılım mimarisi örneğidir; tıbbi, beslenme veya antrenman tavsiyesi değildir. Değerler genel literatür aralıklarıdır. Sağlık durumunuza özel kararlar için bir hekime veya diyetisyene danışın.

⚠️ This page is a software architecture example, not medical, nutrition or training advice. The values are general ranges from the literature. Talk to a doctor or dietitian about decisions specific to your health.

Saha Deneyimleri & ÇözümlerProduction Pitfalls & Solutions

Geliştirirken Karşılaşılan Kritik Zorluklar ve Çözümleri

Critical Engineering Pitfalls and How We Solved Them

7/24 otonom çalışan bir LLM spor koçunu gerçek dünyada devreye alırken tecrübe ettiğimiz en büyük darboğazlar ve mimari çözümleri.

The most significant bottlenecks and architectural workarounds encountered while deploying a 24/7 autonomous LLM personal trainer in production.

1. Telegram Webhook & Buton İletimi1. Telegram Webhook & Inline Button Delivery

Yutulan Callback Query OlaylarıSilent Drops of Callback Queries

Problem: Telegram varsayılan Webhook yapılandırmasında yalnızca message güncellemelerini yönlendirir. Su kaydı ve mobilite kartlarındaki interaktif butonlara tıklandığında oluşan callback_query olayları sunucuya hiç ulaşmıyordu ve butonlar yanıtsız kalıyordu.

Problem: By default, Telegram webhooks only subscribe to message updates. Button clicks on hydration cards and mobility checklists emit callback_query payloads, which were silently dropped before reaching the Edge Function.

Çözüm: setWebhook çağrısı allowed_updates: ["message", "edited_message", "callback_query"] ile açıkça güncellendi. Buton tıklandığında 3 saniye içinde answerCallbackQuery ile toast bildirimi verildi ve editMessageText ile butonlar kaldırılarak kart yerinde güncellendi.

Solution: Explicitly registered allowed_updates: ["message", "edited_message", "callback_query"] via the Telegram API, acknowledged clicks within 3 seconds using answerCallbackQuery, and edited messages in-place with editMessageText.

2. LLM Metin İçi Aksiyon Halüsinasyonu2. Inline Action Block Hallucinations

JSON Kod Bloklarının Metne SızmasıRaw Action Blocks Leaking into Text

Problem: Açık kaynak modeller bazen standart OpenAI tool_calls yapısı yerine metin gövdesi içine [[START_OF_FRONTEND_ACTION_BLOCK]] {"tool": "log_meal", ...} basar. Model araç çağırmamış sayıldığından işlem veritabanına yazılmıyor ve kullanıcıya ham JSON gidiyordu.

Problem: Certain open-weights models occasionally emit [[START_OF_FRONTEND_ACTION_BLOCK]] JSON payloads directly into message content rather than invoking native function calling. The tool wasn't triggered and raw JSON leaked to the user.

Çözüm: Gelen yanıt gövdesinde regex tabanlı aksiyon bloğu yakalayıcı kuruldu; metin içindeki JSON otomatik sentetik bir tool_call'a dönüştürülüp çalıştırıldı. Ayrıca tüm son kullanıcı yanıtları için regex temizleme filtresi devreye alındı.

Solution: Implemented a content-level interceptor that detects raw action blocks, converts them on the fly into synthetic function calls, and applies a strict user-facing sanitizer to strip any technical markup.

3. Özyinelemeli Kesilme & Hafıza Zehirlenmesi3. Recursive Truncation & Memory Poisoning

Tek Harfli Yanıt Döngüleri (**K, G)Single-Token Echo Loops

Problem: Model bir turda yarım kalan veya tek harfli bir cevap (örn. • **K) ürettiğinde, bu metin konuşma geçmişine (coach_messages) yazılıyor ve model sonraki her mesajda geçmişteki bu bozuk yapıyı taklit ederek kesik yanıtlar üretmeye devam ediyordu.

Problem: If a response stopped prematurely (e.g. • **K), saving it to conversation history caused subsequent turns to echo the broken pattern, collapsing future dialogue into single characters or broken markdown tags.

Çözüm: Çift yönlü filtreleme: Kapanmamış markdown tag'i içeren veya 15 karakterden kısa yanıtlar hafızaya alınmadan reddedildi. Hafıza okunurken de bozuk kayıtlar filtrelenerek modele temiz bir bağlam sunuldu.

Solution: Two-way sanity filters: assistant responses shorter than 15 chars or ending in unclosed markdown tags are discarded and retried; dirty records are pruned prior to prompt construction.

4. Model Gecikmesi & Edge Timeout Yönetimi4. Model Latency & Edge Timeout Fallbacks

Büyük Modellerin Süre Aşımı (503/Timeout)High Latency and Service Outages

Problem: Yoğun saatlerde veya büyük modellerde (31B+) akıl yürütme (reasoning) süresi Supabase Edge Function'ın ve Telegram webhook'unun sınırlarını aşıyordu. Bir model kilitlendiğinde tüm sistem cevapsız kalıyordu.

Problem: Large models (31B+) or thinking-heavy prompts exceeded Edge Function execution budgets during peak loads, stalling the webhook and triggering gateway timeouts.

Çözüm: Hiyerarşik model havuzu oluşturuldu (qwen3.8-flash-next öncelikli, auto ve gemma-4-31b yedekli). Her HTTP çağrısına 9.5 saniyelik AbortSignal.timeout eklenerek takılan model anında sonraki hızlı alternatife devredildi.

Solution: Established a multi-model fallback cascade with a 9.5s AbortSignal.timeout per request, falling back from ultra-fast qwen3.8-flash-next (~1.8s) to dynamic auto routing.

5. Türk Mutfağı Porsiyon Belirsizliği5. Turkish Cuisine Portion Ambiguity

"Yumurta Ekmek Falan" Serbest DiliConversational & Unspecified Portions

Problem: Kullanıcı "yumurta ekmek falan yedim" gibi gramajsız konuştuğunda, modelin sürekli soru sorarak diyaloğu kilitlemesi kullanıcı deneyimini zedeliyordu.

Problem: Casual meal descriptions (e.g. "had some eggs and bread") caused conversational deadlocks when the LLM interrogated the user for exact grams before logging.

Çözüm: Standart Türk mutfağı porsiyon kütüphanesi sisteme entegre edildi (2 yumurta + 1 dilim ekmek = 235 kcal, 16g P). Koç varsaydığı porsiyonu şeffafça söyleyerek anında kaydı gerçekleştirir.

Solution: Calibrated reasonable Turkish defaults (2 eggs + 1 slice of bread = 235 kcal, 16g protein), allowing instant database logging while transparently stating the assumed portion.

6. Yaşam Tarzı ve Mesai Saatleri Uyumu6. Lifestyle & Office Hour Guardrails

Mesai Ortasında Koşu Önerisi ÇelişkisiIll-Timed Midday Workout Suggestions

Problem: Botun hafta içi mesai saatlerinin (08:00 - 18:00) ortasında kullanıcıya dışarıda koşu veya ağır antrenman önermesi gerçek hayat ritmiyle çelişiyordu.

Problem: The AI occasionally recommended outdoor runs during 08:00-18:00 office hours, violating the athlete's work schedule.

Çözüm: Hafta içi mesai saatleri kuralı bağlama eklendi: Hafta içi koşu ve ana antrenmanlar daima 18:00 paydos sonrasına planlanır. 15:30'da masabaşı mobilite ve 17:45'te mesai çıkışı koşu brifingi otomatik tetiklenir.

Solution: Embedded strict work hours (08:00-18:00) into the prompt context: workouts are strictly scheduled post-18:00, paired with a 15:30 desk mobility alert and a 17:45 pre-run briefing.

Açık ŞemaOpen Schema

Supabase Veritabanı ve Cron Yapılandırması

Supabase Database and Cron Setup

Sistemi kendi Supabase projenizde ayağa kaldırmak için gereken SQL şeması.

The SQL schema you need to stand the system up in your own Supabase project.

-- 1. Koçluk ve Telemetri Tabloları1. Coaching and Telemetry Tables
create table if not exists public.daily_metrics (
  day date primary key,
  steps integer,
  resting_hr integer,
  weight_kg numeric(5,2),
  updated_at timestamptz not null default now()
);

create table if not exists public.sleep_sessions (
  id uuid primary key default gen_random_uuid(),
  start_time timestamptz not null,
  end_time timestamptz not null,
  duration_min integer not null,
  stages jsonb,
  source text not null
);

create table if not exists public.meal_logs (
  id bigint generated always as identity primary key,
  day date not null default current_date,
  meal_type text not null, -- kahvalti, ogle, aksam, ara_ogun
  description text not null,
  calories integer not null,
  protein_g numeric(6,1) not null default 0,
  carbs_g numeric(6,1) not null default 0,
  fat_g numeric(6,1) not null default 0,
  created_at timestamptz not null default now()
);

create table if not exists public.water_logs (
  id bigint generated always as identity primary key,
  day date not null default current_date,
  amount_ml integer not null default 250,
  created_at timestamptz not null default now()
);

-- 2. 7/24 Proaktif pg_cron Tetikleyicileri (Türkiye Saati / UTC+3)2. 24/7 proactive pg_cron triggers (Türkiye time / UTC+3)
-- Sabah 08:30 TR (05:30 UTC): Uyku & Hava Durumu BrifingiMorning 08:30 TR (05:30 UTC): sleep & weather briefing
select cron.schedule('pt_morning', '30 5 * * *', 
  $$select net.http_post(url := 'https://[PROJECT].supabase.co/functions/v1/telegram-bot?cron=morning')$$);

-- Mesai İçi Su Hatırlatma Kartları (Hafta İçi 10:30, 12:30, 14:30, 16:30 TR)Desk Hours Water Reminder Cards (Weekdays 10:30, 12:30, 14:30, 16:30 TR)
select cron.schedule('pt_water_card_1', '30 7 * * 1-5', 
  $$select net.http_post(url := 'https://[PROJECT].supabase.co/functions/v1/telegram-bot?cron=water_card')$$);

-- Masabaşı Mobilite Molası (Hafta İçi 15:30 TR / 12:30 UTC)Desk Mobility Micro-Break (Weekdays 15:30 TR / 12:30 UTC)
select cron.schedule('pt_mobility', '30 12 * * 1-5', 
  $$select net.http_post(url := 'https://[PROJECT].supabase.co/functions/v1/telegram-bot?cron=mobility')$$);

-- Mesai Bitimi & Koşu Öncesi Brifingi (Hafta İçi 17:45 TR / 14:45 UTC)Work End & Pre-Run Briefing (Weekdays 17:45 TR / 14:45 UTC)
select cron.schedule('pt_pre_run', '45 14 * * 1-5', 
  $$select net.http_post(url := 'https://[PROJECT].supabase.co/functions/v1/telegram-bot?cron=pre_run')$$);

-- Öğle 13:45 TR: Öğün Atlama & Metabolizma KontrolüLunch 13:45 TR: skipped-meal & metabolism check
select cron.schedule('pt_lunch', '45 10 * * *', 
  $$select net.http_post(url := 'https://[PROJECT].supabase.co/functions/v1/telegram-bot?cron=lunch_check')$$);

-- Akşam 19:45 TR: Akşam Yemeği & Kapanış ÖzetiEvening 19:45 TR: dinner & remaining budget
select cron.schedule('pt_dinner', '45 16 * * *', 
  $$select net.http_post(url := 'https://[PROJECT].supabase.co/functions/v1/telegram-bot?cron=dinner_check')$$);