# business-analysis

Adopt this skill: https://proskills.md/skills/other/abdobasyioni-business-analysis-skill

Page: https://proskills.md/skills/other/abdobasyioni-business-analysis-skill
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: SKILL.md
size: 53478
sha: ab7b9c981e740c550ccc22b58ebcb41f27923dd1
upstream: https://github.com/abdobasyioni/business-analysis-skill/blob/HEAD/SKILL.md
truncated: true

````text
---
name: business-analysis
description: Elite Business Intelligence, Data Analytics, Financial Analysis, and Executive Strategy consulting on uploaded spreadsheets (Excel/CSV). Triggers when the user uploads or references a tabular dataset and wants insights, KPIs, root-cause analysis, SWOT, opportunities, risks, forecasts, executive recommendations, or an interactive HTML dashboard. Produces Big-Four-style consulting output in Arabic RTL.
---

# Business Analysis

You are **Business Analysis** — an elite AI Business Intelligence, Data Analytics, Financial Analysis, and Executive Strategy Consultant. Your mission is NOT to describe data. Your mission is to discover business opportunities, identify hidden risks, explain WHY things happened, predict what will happen next, and provide executive-level recommendations.

Think and act like a consulting team: Senior Business Analyst, Senior Data Analyst, BI Consultant, Strategy Consultant, Financial Analyst, Revenue Manager, Sales Director, Operations Manager, and CEO Advisor. Never act like a chatbot. Act like a consulting company.

## ⚡ Execution Protocol (READ FIRST — this governs HOW you work, and overrides any habit of writing HTML by hand)

The single biggest failure mode of this skill is **token exhaustion**: hand-writing a 65 KB HTML file (CSS + chart engine + nav + footer + every section) costs ~25,000 output tokens per report, of which ~80% is byte-identical every single time. That is what makes runs stall mid-generation and hit the limit. The shell is therefore **pre-built and shipped with this skill**. You never write it again.

### The three assets (never rewrite them, never inline their contents)

| File | What it is | Your job |
|---|---|---|
| `assets/profile_data.py` | one-shot workbook profiler | run it once, read its output |
| `assets/template.html` | the entire report shell — CSS, palette, dark mode, responsive layer, mobile drawer, chart engine, table sorting, branded footer | **never open it, never copy it, never regenerate it** |
| `assets/build_report.py` | deterministic assembler | run it once at the end |

### Mandatory 4-step run

**Step 1 — Profile once (1 bash call).**

```bash
python3 <skill>/assets/profile_data.py /mnt/user-data/uploads/<file> --rows 3
```

هذه هي جولة الاستكشاف الوحيدة المسموح بها. لا تقرأ الملف مرة تانية بعد كده، ولا تطبع أي DataFrame خام.

**Step 2 — Analyze in code, not in context (1–2 bash calls).**
Write ONE `analyze.py` that does the whole pipeline (clean → engineer → KPIs → period deltas → leaderboards → ABC/Pareto/RFM → correlations → anomalies → forecast) and ends by writing `analysis.json`. Then `print` only a **compact digest** — headline numbers, top/bottom 10 lists, deltas, flags. Hard ceiling: **150 printed lines**. Everything else stays in the JSON file on disk.

> ⛔ Never `print(df)`, `print(df.head(50))`, `df.to_string()` on a full frame, or dump raw rows. Loading rows into context is the second-largest token sink after hand-writing HTML.

**Step 3 — Write only the two variable artifacts.**

- `sections.html` — the `<section>` blocks only: KPI cards, tables, insight cards, SWOT, risk matrix, recommendations, and an empty `<div id="chartX"></div>` wherever a chart goes. **No `<style>`, no `<script>`, no `<html>`/`<head>`/`<body>`, no footer, no nav markup.** Use the existing class names (`card`, `grid g4`, `kpi`, `insight crit|warn|good|note`, `tbl-wrap`, `swot-grid`, `pill`, `takeaway`, `chart-title`, `sec-head`).
- `report.json` — metadata + nav + chart series:

```json
{
  "title": "التقرير التنفيذي — ...",
  "subtitle": "الفترة التحليلية: ...",
  "footnote": "جميع الأرقام مستخرجة من ملف ...",
  "nav": [{"group":"البداية","items":[{"id":"exec","label":"الملخص التنفيذي","icon":"📌"}]}],
  "charts": {
    "chartProducts": {"type":"hbar","color":"--teal","data":[{"name":"كزبرة","v":38543}]},
    "chartDaily":    {"type":"line","color":"--teal","data":[{"d":"07-01","v":19624}]},
    "chartCorr":     {"type":"corr","data":[]}
  }
}
```

### Chart library (10 types — pick by analytical question, never by decoration)

| type | data shape | `opts` | use it for |
|---|---|---|---|
| `hbar` | `[{name, v, label?}]` | — | ranking / leaderboards (default) |
| `line` | `[{d, v}]` | — | trend over time |
| `pareto` | `[{name, v, label?}]` | `barLabel` | concentration & ABC — bars + cumulative % + 80% reference line |
| `waterfall` | `[{name, v, type?, label?}]` | — | profit bridge, variance bridge. `type:"total"` pins a bar to zero (opening/subtotal/closing); other bars are deltas |
| `scatter` | `[{name, x, y, r?, tag?}]` | `xLabel, yLabel, rLabel, xRef, yRef` | portfolio quadrants — revenue vs margin, bubble = volume. Reference lines default to the means |
| `stacked` | `{categories:[], series:[{name, values:[], color?}]}` | — | mix over time (product / channel mix) |
| `grouped` | same as `stacked` | — | side-by-side period or entity comparison |
| `combo` | `[{name, bar, line, barLabel?}]` | `barLabel, lineLabel, lineSuffix` | value vs rate on a second axis — revenue vs discount %, sales vs return % |
| `heatmap` | `{rows:[], cols:[], values:[[..]]}` | — | matrix: branch × month seasonality, product × branch coverage. `null` = no data |
| `donut` | `[{name, v, label?}]` | `centerLabel, centerValue` | share of total. Max 6 slices, use sparingly |

Colors are palette variables: `--teal`, `--blue`, `--purple`, `--amber`, `--red`, `--green`, `--navy`. Every chart renders legends, tooltips (hover shows the full name and value), RTL category ordering, and a visible error box if its data is malformed — one bad chart never blanks the report.

**Chart selection discipline:** a `donut` where a `pareto` belongs is a wasted chart. Concentration → `pareto`. "Where did the money go" → `waterfall`. "Who should I keep/fix/exit" → `scatter`. "What changed in the mix" → `stacked`. "Is the rate moving against the volume" → `combo`. "Where is the seasonal or coverage hole" → `heatmap`.

Legacy: `corr` (two normalized lines) still works. `hbar` data `{name, v, label?}` — set `label` to a pre-formatted display string such as `"223.13 مليون"` and the renderer sizes its gutter around it automatically; omit it and the raw number is formatted with thousands separators), `line` (data `{d,v}`), `corr`. Colors are palette variables: `--teal`, `--blue`, `--purple`, `--amber`, `--red`, `--green`. The renderer wires every entry in `charts` to its `<div id>` automatically — **do not write a `render()` function, a chart function, or any `<script>` tag.**

Generate `report.json` from `analyze.py` (dump the series straight from pandas) rather than typing numbers by hand — it is faster, and it removes transcription errors.

**Step 4 — Assemble (1 bash call).**

```bash
python3 <skill>/assets/build_report.py sections.html report.json /mnt/user-data/outputs/business-analysis-report.html
```

Then present the file. The builder runs a **structural gate** and exits non-zero on: unreplaced placeholders, unbalanced `<style>`/`<script>`/`<body>` tags (the classic cause of a blank white report — everything after an unclosed `<style>` renders as CSS text), an empty or shell-contaminated `sections.html`, and any chart declared in `report.json` without a matching `<div id>` (or vice versa).

**If the build fails, fix the reported error and rebuild — never hand-patch the output HTML.**

**Step 5 — Verify before presenting (mandatory, 1 bash call).** A successful exit code is not proof the report renders. Run:

```bash
python3 - <<'EOF'
s=open('/mnt/user-data/outputs/business-analysis-report.html',encoding='utf-8').read()
print('KB', round(len(s.encode())/1024,1))
print('body_content', len(s.split('<body>')[1].split('<footer')[0]))
print('sections', s.count('<section'), 'charts', s.count('id="chart'))
print('style_closed', '</style>' in s, 'script_closed', s.count('</script>')==s.count('<script>'))
EOF
```

`body_content` under ~3000 characters means the report is effectively empty — investigate be
````

## File: README.md
size: 9261
sha: 5ef12d9997f193cd24e04e8c9e9ac3aab9b3ec36
upstream: https://github.com/abdobasyioni/business-analysis-skill/blob/HEAD/README.md

````text
<div align="right" dir="rtl">

# 🎯 Business Analysis Skill

**مهارة تحليل أعمال تنفيذية بمستوى شركات الاستشارات الكبرى (Big Four) — مبنية لـ Claude.**

من ملف Excel أو CSV واحد، السكل بتطلع **تقرير HTML تفاعلي كامل** فيه ملخص تنفيذي، مؤشرات KPIs، تحليل جذور الأسباب، SWOT، فرص، مخاطر، توقعات، وتوصيات — كله بالعربي RTL وبتصميم Enterprise-grade.

---

## ✨ ليه السكل ده مختلف

معظم أدوات التحليل بتوصف الداتا. السكل ده بيفكر زي **فريق استشارات كامل** جوه Claude:

> Senior Business Analyst · Senior Data Analyst · BI Consultant · Strategy Consultant · Financial Analyst · Revenue Manager · Sales Director · Operations Manager · CEO Advisor

بمعنى إنه ما بيقولش لك "المبيعات نزلت ٧٪". بيقولك:
- **إيه اللي حصل؟** المبيعات نزلت ٧٪ الشهر ده
- **ليه؟** فرع الجيزة نزل ١٨٪ بسبب تراجع عميلين كبار (تركّز ٢٣٪ من الربح)
- **إيه أثره؟** خسارة ربح متوقعة ٤١٠ ألف جنيه لو استمر
- **إيه القرار؟** استرداد العميلين + توسيع قاعدة B في القاهرة الكبرى
- **إيه المخاطر؟** لو ما اتحركناش خلال أسبوعين، الفرع يخسر مركزه في التوب ٣

---

## 🏗️ المعمارية — ليه بتشتغل بدون ما تعلّق

السكل مبني على **٣ أصول جاهزة** بتمنع أكبر مشكلتين في تقارير Claude:
- **استهلاك التوكنز** — الشيل جاهز، مش بيتكتب من الأول كل مرة
- **الوقوع في نص التقرير** — التجميع الحتمي بيمنع أي `<style>` مفتوح أو ملف فاضي

| الملف | وظيفته |
|---|---|
| `assets/profile_data.py` | Profiler بيقرأ الملف مرة واحدة ويطلع خريطة كاملة عن الأوراق والأعمدة والعلاقات |
| `assets/template.html` | قالب التقرير الكامل: CSS + Dark mode + Mobile drawer + محرك رسوم بياني بـ ١٠ أنواع + Footer برانديد |
| `assets/build_report.py` | Assembler حتمي بيدمج `sections.html` + `report.json` في ملف HTML واحد، وبيرفض التسليم لو فيه أي خطأ بنيوي |

النتيجة: كل تقرير بيخلص في **٤–٥ Bash calls** بدل ١٠–٢٠، وبـ **~٥٠٠٠ توكن output** بدل ~٢٥٠٠٠.

---

## 📊 اللي بيطلعه التقرير

**الأقسام الأساسية:**
- الملخص التنفيذي + Business Health Score
- تقييم جودة البيانات (٠–١٠٠) مع شرح كل ملاحظة
- مجموعة KPIs مقترحة بذكاء حسب طبيعة البيانات
- تحليل الفترة الحالية مقابل السابقة (Period-over-Period)
- استقرار الترتيب (Leaderboard Stability) — مين اتغير مركزه وليه
- التركّز والاعتماد (Pareto/ABC) — مين شايل ٨٠٪ من الربح
- Profit Bridge (Waterfall) — الفلوس راحت فين
- Portfolio Quadrants (Scatter) — إيرادات × هامش × حجم
- Heatmap للموسمية × الفروع أو المنتجات
- SWOT مبني على أرقام حقيقية مش كلام عام
- Risk Matrix (حرج / عالي / متوسط / منخفض)
- توصيات مسعّرة بأثر مالي متوقع
- توقعات مستقبلية (Forecast) لما يكون فيه تاريخ كافي

**تحليلات متقدمة عبر الأوراق (لو الملف فيه أكتر من شيت):**
- كشف تلقائي للعلاقات ومفاتيح الربط (١:١، ١:many)
- مطابقة الإجماليات بين الأوراق (Reconciliation)
- تحليل Sales × Returns × Discounts × Expenses × Collections × Inventory كنموذج واحد
- تحديد الفجوات (إيه السؤال التنفيذي اللي مش هينفع نجاوبه لأن الشيت الفلاني ناقص)

---

## 📈 محرك الرسوم البيانية

**١٠ أنواع رسوم**، كلها بتحترم العربي RTL وبتشتغل على الموبايل والديسكتوب:

| النوع | بيستخدم لـ |
|---|---|
| `hbar` | الترتيب واللوحات الصدارية |
| `line` | الاتجاه الزمني |
| `pareto` | التركّز والـ ABC (٨٠/٢٠) |
| `waterfall` | جسور الربح والانحرافات |
| `scatter` | تحديد المحفظة (إيراد × هامش × حجم) |
| `stacked` / `grouped` | تطور المزيج |
| `combo` | القيمة × النسبة (مبيعات × نسبة الخصم) |
| `heatmap` | المصفوفات (فرع × شهر) |
| `donut` | الحصة من الإجمالي |

كل رسم بيبقى معاه **عنوان + Takeaway تنفيذي بجملة** (مش زخرفة).

---

## 🚀 إزاي تستخدمها

### الطريقة الأولى — Claude.ai (الأسهل)

انسخ فولدر السكل ده في مكان مهاراتك الشخصية، وClaude هيفعّلها تلقائياً لما ترفع أي ملف Excel أو CSV.

### الطريقة الثانية — Claude Code

```bash
git clone https://github.com/YOUR_USERNAME/business-analysis-skill.git ~/.claude/skills/business-analysis
```

بعدها، أول مرة ترفع فيها ملف بيانات، Claude هيشغّل السكل تلقائياً.

### الطريقة الثالثة — استدعاء مباشر

```
/business-analysis
[ارفع ملف Excel أو CSV]
```

**مافيش أسئلة توضيحية.** السكل مصمم إنه يفهم الملف لوحده ويشتغل من غير ما يسأل عن أسماء الأعمدة أو الوحدات — لأن ده اللي بيميّز أدوات الاستشارات الحقيقية عن الشات بوت.

---

## 📁 هيكل الريبو

```
business-analysis-skill/
├── SKILL.md                    # المهارة كاملة (٥٠٠+ سطر)
├── README.md                   # اللي بتقراه دلوقتي
├── LICENSE                     # MIT
├── CHANGELOG.md                # سجل الإصدارات
└── assets/
    ├── profile_data.py         # Profiler للملفات
    ├── template.html           # قالب التقرير (٥٠KB)
    └── build_report.py         # Assembler حتمي
```

---

## 🎨 الفلسفة اللي وراها

**لا تقرأ مؤشر لوحده.** الخصم لازم يتقرا مع الحجم، والعائد مع العميل، والتحصيل مع شروط الائتمان. أي توصية مبنية على مؤشر واحد معزول = نصيحة غلط.

**FACT / LIKELY / HYPOTHESIS.** كل استنتاج بيتوسم بمستوى الثقة. مش كل حاجة "علينا فوراً نعمل" — الثقة جزء من الرسالة.

**اذكر السبب واذكر الرافعة.** كل نتيجة تقول: هل السعر ولا الحجم ولا المزيج ولا التغطية ولا الائتمان هو اللي حرّكها؟

**اقتصاد العميل مش بس الإيراد.** العملاء بيتصنفوا على أساس: الإيراد، الربح الإجمالي والصافي، الخصم، العائد، أيام التحصيل، مخاطر الائتمان، تكلفة النقل، وتأثير التدفق النقدي — مش الإيراد لوحده.

---

## 🛠️ المتطلبات

- Python 3.8+
- pandas, openpyxl (للـ Excel)
- Claude Opus 4.5+ أو Sonnet 4.6+ (الموديل بيحدد جودة التوصيات)

**بدون مكتبات خارجية في التقرير النهائي** — كل CSS و JS مضمّنين في ملف HTML واحد بينفتح على أي متصفح Offline.

---

## 📄 الرخصة

MIT License — استخدم، عدّل، وزّع بحرية. لو استخدمت السكل في مشروع تجاري أو محتوى منشور، إشارة للمصدر بتبقى محل تقدير.

---

## 👤 عن المطوّر

**م. عبدالرحمن محمود علي بسيوني**

محلل بيانات ومطوّر أعمال متخصص في FMCG المصرية، صاحب خبرة في تحليل التوزيع متعدد الفروع، الموسمية، ونماذج Volume-Price-Mix. مطوّر أنظمة ERP و BI مخصصة على Google Apps Script و Power BI و Python.

- 💼 [LinkedIn](https://www.linkedin.com/in/abdelrahman-mahmoud-ali-basiony)
- 📘 [Facebook](https://www.facebook.com/share/1SstGGoSNM/)

---

## 🤝 المساهمة

أي اقتراح، مشكلة، أو تحسين → افتح Issue أو Pull Request. السكل ده حي وبيتطور، وأي إضافة من مجتمع محللي البيانات محل ترحيب.

---

<div align="center">

**⭐ لو السكل ساعدك، اديها Star على GitHub — ده بيوصلها لناس تانية محتاجاها.**

</div>

</div>
````

## File: assets/build_report.py
size: 4049
sha: 8db226cbc7b6bb598c6b26e935d21286ab2d3736
upstream: https://github.com/abdobasyioni/business-analysis-skill/blob/HEAD/assets/build_report.py

```text
#!/usr/bin/env python3
"""
build_report.py — assembles the final self-contained HTML report.

The model NEVER writes CSS, chart JS, nav, or footer. It only writes:
  sections.html   -> the <section> blocks (content + narrative)
  report.json     -> {"title","subtitle","footnote","nav":[...],"charts":{...}}

Usage:
  python3 build_report.py sections.html report.json out.html
"""
import json
import sys
from pathlib import Path

TPL = Path(__file__).with_name("template.html")

def build_nav(nav):
    """nav = [{"group":"البداية","items":[{"id":"exec","label":"الملخص","icon":"📌"}]}]"""
    out = []
    for grp in nav:
        out.append(f'  <div class="grp">{grp["group"]}</div>')
        for it in grp["items"]:
            icon = it.get("icon", "•")
            out.append(f'  <a href="#{it["id"]}">{icon} {it["label"]}</a>')
    return "\n".join(out)

def main():
    if len(sys.argv) != 4:
        sys.exit("usage: build_report.py sections.html report.json out.html")
    sections_path, json_path, out_path = sys.argv[1:4]

    tpl = TPL.read_text(encoding="utf-8")
    sections = Path(sections_path).read_text(encoding="utf-8")
    meta = json.loads(Path(json_path).read_text(encoding="utf-8"))

    charts = json.dumps(meta.get("charts", {}), ensure_ascii=False, separators=(",", ":"))

    html = (
        tpl.replace("__TITLE__", meta.get("title", "التقرير التنفيذي"))
        .replace("__SUBTITLE__", meta.get("subtitle", ""))
        .replace("__FOOTNOTE__", meta.get("footnote", "تقرير تحليل أعمال تنفيذي"))
        .replace("__NAV__", build_nav(meta.get("nav", [])))
        .replace("__SECTIONS__", sections)
        .replace("__CHARTS__", charts)
    )

    validate(html, sections, meta)

    Path(out_path).write_text(html, encoding="utf-8")
    kb = len(html.encode("utf-8")) / 1024
    print(f"OK  {out_path}  {kb:.1f} KB  |  sections={sections.count('<section')}  charts={len(meta.get('charts', {}))}")

def validate(html, sections, meta):
    """Structural gate. A blank-rendering report must never leave this script."""
    errs = []

    for token in ("__TITLE__", "__SUBTITLE__", "__SECTIONS__", "__CHARTS__", "__NAV__", "__FOOTNOTE__"):
        if token in html:
            errs.append(f"placeholder {token} not replaced")

    # unclosed <style> or <script> swallows the whole document -> blank white page
    for tag in ("style", "script", "head", "body", "html"):
        o, c = html.count(f"<{tag}>") + (html.count(f"<{tag} ") if tag in ("script", "body", "html") else 0), html.count(f"</{tag}>")
        if o != c:
            errs.append(f"tag <{tag}> unbalanced: {o} open vs {c} close")

    if "</style>" not in html:
        errs.append("missing </style> — everything after <style> renders as CSS text (blank page)")

    # content actually present
    if sections.count("<section") == 0:
        errs.append("sections.html contains no <section> block")
    if len(sections.strip()) < 200:
        errs.append("sections.html is suspiciously small")

    # every declared chart must have a container, and every empty placeholder div must have a series
    import re
    for cid in meta.get("charts", {}):
        if f'id="{cid}"' not in html:
            errs.append(f'chart "{cid}" declared in report.json but no <div id="{cid}"> in sections.html')
    placeholders = set(re.findall(r'<div\s+id="([^"]+)"\s*>\s*</div>', sections))
    for orphan in placeholders - set(meta.get("charts", {})):
        errs.append(f'<div id="{orphan}"> is an empty placeholder but has no series in report.json')

    # sections must not carry their own shell
    for banned in ("<style", "<script", "<!DOCTYPE", "<footer"):
        if banned.lower() in sections.lower():
            errs.append(f"sections.html must not contain {banned} — the shell is in template.html")

    if errs:
        print("BUILD FAILED:", file=sys.stderr)
        for e in errs:
            print("  ✗ " + e, file=sys.stderr)
        sys.exit(1)

if __name__ == "__main__":
    main()
```

## File: assets/profile_data.py
size: 4202
sha: 0b8e4b0448dd263114b615d44afb8cfee26f6cf4
upstream: https://github.com/abdobasyioni/business-analysis-skill/blob/HEAD/assets/profile_data.py

```text
#!/usr/bin/env python3
"""
profile_data.py — ONE-SHOT workbook profiler.

Purpose: give the model everything it needs to plan the analysis in a single
bounded output (~120 lines), so it never loads raw rows into context.
NEVER print a whole dataframe. This script is the only exploration pass allowed.

Usage:
  python3 profile_data.py <file.xlsx|file.csv> [--rows 3]
"""
import sys
import warnings
from pathlib import Path

import pandas as pd

warnings.filterwarnings("ignore")
pd.set_option("display.width", 200)

MAX_UNIQ = 8          # sample values shown per column
MAX_COLS_DETAIL = 40  # columns detailed per sheet

def load(path):
    p = Path(path)
    if p.suffix.lower() in (".csv", ".tsv", ".txt"):
        sep = "\t" if p.suffix.lower() == ".tsv" else None
        return {"data": pd.read_csv(p, sep=sep, engine="python")}
    xls = pd.ExcelFile(p)
    return {name: xls.parse(name) for name in xls.sheet_names}

def kind(s: pd.Series) -> str:
    if pd.api.types.is_numeric_dtype(s):
        return "num"
    if pd.api.types.is_datetime64_any_dtype(s):
        return "date"
    nn = s.dropna().astype(str)
    if len(nn) and nn.str.match(r"^\s*\d{1,4}[-/]\d{1,2}[-/]\d{1,4}").mean() > 0.7:
        return "date?"
    return "txt"

def profile_sheet(name, df, sample_rows):
    n, m = df.shape
    print(f"\n=== SHEET: {name}  rows={n}  cols={m}")
    if n == 0:
        print("  (empty)")
        return
    dup = int(df.duplicated().sum())
    print(f"  duplicate_rows={dup}")

    cols = list(df.columns)[:MAX_COLS_DETAIL]
    for c in cols:
        s = df[c]
        k = kind(s)
        miss = round(s.isna().mean() * 100, 1)
        nuq = s.nunique(dropna=True)
        line = f"  - {str(c)[:38]:<38} {k:<5} miss={miss:>5}%  uniq={nuq}"
        if k == "num":
            d = s.dropna()
            if len(d):
                line += (
                    f"  min={d.min():,.2f} max={d.max():,.2f}"
                    f" sum={d.sum():,.2f} neg={int((d < 0).sum())} zero={int((d == 0).sum())}"
                )
        else:
            vals = s.dropna().astype(str).value_counts().head(MAX_UNIQ).index.tolist()
            line += "  e.g. " + " | ".join(v[:22] for v in vals)
        print(line)

    if len(df.columns) > MAX_COLS_DETAIL:
        print(f"  ... +{len(df.columns) - MAX_COLS_DETAIL} more columns")

    if sample_rows:
        print(f"  --- first {sample_rows} rows ---")
        print(df.head(sample_rows).to_string(max_colwidth=18))

def relationships(sheets):
    """Detect candidate join keys by column-name and value overlap."""
    print("\n=== CANDIDATE JOIN KEYS")
    names = list(sheets)
    found = False
    for i in range(len(names)):
        for j in range(i + 1, len(names)):
            a, b = sheets[names[i]], sheets[names[j]]
            for ca in a.columns:
                for cb in b.columns:
                    if str(ca).strip().lower() != str(cb).strip().lower():
                        continue
                    va = set(a[ca].dropna().astype(str))
                    vb = set(b[cb].dropna().astype(str))
                    if not va or not vb:
                        continue
                    ov = len(va & vb) / min(len(va), len(vb))
                    if ov > 0.3:
                        card = "1:1" if len(va) == len(vb) else "1:many"
                        print(f"  {names[i]}.{ca}  <->  {names[j]}.{cb}   overlap={ov:.0%}  {card}")
                        found = True
    if not found:
        print("  none detected")

def main():
    if len(sys.argv) < 2:
        sys.exit("usage: profile_data.py <file> [--rows N]")
    path = sys.argv[1]
    sample_rows = 3
    if "--rows" in sys.argv:
        sample_rows = int(sys.argv[sys.argv.index("--rows") + 1])

    sheets = load(path)
    print(f"FILE: {Path(path).name}   sheets={len(sheets)}")
    print("SHEET INVENTORY: " + ", ".join(f"{k}({v.shape[0]}x{v.shape[1]})" for k, v in sheets.items()))
    for name, df in sheets.items():
        profile_sheet(name, df, sample_rows)
    if len(sheets) > 1:
        relationships(sheets)
    print("\n=== END PROFILE (plan the analysis from this; do NOT re-read raw rows)")

if __name__ == "__main__":
    main()
```

## File: assets/template.html
size: 49850
sha: 47f4e3e513f898c7db9722fd30454e61fea8b5d8
upstream: https://github.com/abdobasyioni/business-analysis-skill/blob/HEAD/assets/template.html

Content is not inlined in the catalog. Read the upstream file: https://github.com/abdobasyioni/business-analysis-skill/blob/HEAD/assets/template.html

## File: .gitignore
size: 480
sha: 430211e7fb8e0110519047e71271d67db55e9d13
upstream: https://github.com/abdobasyioni/business-analysis-skill/blob/HEAD/.gitignore

```text
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
env/
venv/
.venv/
*.egg-info/
dist/
build/

# Analysis outputs (تقارير وتحليلات مؤقتة)
*.html
!assets/template.html
analysis.json
sections.html
report.json
profile_output.txt

# Data files (مالنا دعوة نرفع بيانات العملاء)
*.xlsx
*.xls
*.csv
*.tsv
/mnt/

# OS
.DS_Store
Thumbs.db
desktop.ini

# Editors
.vscode/
.idea/
*.swp
*.swo
*~
.claude/

# Environment
.env
.env.local
*.log
```

## File: CHANGELOG.md
size: 1451
sha: 34768fde58162401fbaf24e4e88f8704a4faf394
upstream: https://github.com/abdobasyioni/business-analysis-skill/blob/HEAD/CHANGELOG.md

```text
<div align="right" dir="rtl">

# سجل الإصدارات

كل التغييرات الملحوظة في هذه المهارة موثقة في هذا الملف.

الصيغة مبنية على [Keep a Changelog](https://keepachangelog.com/ar/1.1.0/)،
والمشروع يتبع [الإصدار الدلالي](https://semver.org/lang/ar/).

## [1.0.0] — 2026-08-03

### الإصدار الأول العلني

- إطلاق المهارة كاملة (SKILL.md بأكثر من ٥٠٠ سطر تعليمات).
- تضمين الأصول الثلاثة الجاهزة:
  - `profile_data.py` — أداة استكشاف البيانات في استدعاء واحد.
  - `template.html` — قالب التقرير الكامل (CSS + JS + Dark mode + Mobile drawer).
  - `build_report.py` — أداة تجميع حتمية مع بوابة تحقق بنيوي.
- محرك رسوم بيانية بعشرة أنواع: hbar, line, pareto, waterfall, scatter,
  stacked, grouped, combo, heatmap, donut.
- دعم كامل للعربي RTL في كل الرسوم والجداول والتنقّل.
- وضع Economy Mode للجلسات المقيدة.
- تحليل متعدد الأوراق مع اكتشاف تلقائي للعلاقات ومطابقة الإجماليات.
- محرك الربط بين المؤشرات (Cross-Metric Linkage) — الخصم مع الحجم،
  العائد مع العميل، التحصيل مع الائتمان.

</div>
```

## File: LICENSE
size: 1088
sha: 658f420fe5738d786791d8a5836fc4d3a18fb886
upstream: https://github.com/abdobasyioni/business-analysis-skill/blob/HEAD/LICENSE

```text
MIT License

Copyright (c) 2026 Abdelrahman Mahmoud Ali Basiony

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
