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
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
import random
import string
from fastapi import APIRouter, Query, Depends, HTTPException
from fastapi.responses import HTMLResponse
from typing import Optional

# ==========================
# πŸ” Auth & Configuration
# ==========================
# Try to import the auth system, otherwise mock it for standalone use
try:
    from app.routers.auth.system import get_current_user
except ImportError:
    def get_current_user(): return {"username": "Anonymous"}

AUTH_ENABLED = False # Set to True to enforce login

def auth_dependency():
    return Depends(get_current_user) if AUTH_ENABLED else None

# ==========================
# πŸ› οΈ Router Setup
# ==========================
router = APIRouter(
    prefix="/security",
    tags=["Password Tools"],
)

# ==========================
# 🎲 Password Logic (API)
# ==========================
@router.get("/generate-password")
def generate_password(
    length: int = Query(16, ge=8, le=128, description="Length of the password"),
    include_uppercase: bool = True,
    include_lowercase: bool = True,
    include_numbers: bool = True,
    include_symbols: bool = True,
    exclude_ambiguous: bool = False,
    current_user: dict = auth_dependency()
):
    """
    Generates a cryptographically strong random password with advanced options.
    """
    # Character Sets
    lower = string.ascii_lowercase
    upper = string.ascii_uppercase
    nums = string.digits
    syms = "!@#$%^&*()_+-=[]{}|;:,.<>?"
    ambiguous = "il1Lo0O"

    # Filter ambiguous characters if requested
    if exclude_ambiguous:
        lower = "".join([c for c in lower if c not in ambiguous])
        upper = "".join([c for c in upper if c not in ambiguous])
        nums = "".join([c for c in nums if c not in ambiguous])
        syms = "".join([c for c in syms if c not in ambiguous])

    # Build Pool
    pool = ""
    guaranteed_chars = []

    if include_lowercase:
        pool += lower
        guaranteed_chars.append(random.choice(lower))
    if include_uppercase:
        pool += upper
        guaranteed_chars.append(random.choice(upper))
    if include_numbers:
        pool += nums
        guaranteed_chars.append(random.choice(nums))
    if include_symbols:
        pool += syms
        guaranteed_chars.append(random.choice(syms))

    if not pool:
        raise HTTPException(status_code=400, detail="At least one character type must be selected.")

    # Generate remaining characters
    remaining_length = length - len(guaranteed_chars)
    if remaining_length < 0:
        password_chars = guaranteed_chars[:length]
    else:
        password_chars = guaranteed_chars + [random.choice(pool) for _ in range(remaining_length)]

    # Shuffle to remove predictable patterns
    random.shuffle(password_chars)
    final_password = "".join(password_chars)

    # Calculate basic entropy/strength
    pool_size = len(pool)
    entropy = length * (len(bin(pool_size)) - 2) 
    
    strength = "Weak"
    if entropy > 50: strength = "Medium"
    if entropy > 80: strength = "Strong"
    if entropy > 120: strength = "Very Strong"

    user_info = current_user.get("username", "Anonymous") if current_user else "Anonymous"

    return {
        "requested_by": user_info,
        "password": final_password,
        "length": length,
        "strength": strength,
        "entropy_bits": int(entropy)
    }


# ==========================
# 🎨 Modern UI Endpoint
# ==========================
# Path becomes: /security/password-generator/ui
@router.get("/password-generator/ui", response_class=HTMLResponse)
async def password_ui():
    html_content = """
    <!DOCTYPE html>
    <html lang="en" data-theme="light">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Password Tool</title>
        <link rel="preconnect" href="https://fonts.googleapis.com">
        <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
        <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&family=JetBrains+Mono:wght@500&display=swap" rel="stylesheet">
        
        <style>
            :root {
                --primary: #6366f1;
                --primary-hover: #4f46e5;
                --bg-body: #f8fafc;
                --bg-card: #ffffff;
                --text-main: #0f172a;
                --text-sub: #64748b;
                --border: #e2e8f0;
                --input-bg: #f1f5f9;
                --success: #10b981;
                --shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);
            }

            [data-theme="dark"] {
                --primary: #818cf8;
                --primary-hover: #6366f1;
                --bg-body: #0f172a;
                --bg-card: #1e293b;
                --text-main: #f8fafc;
                --text-sub: #94a3b8;
                --border: #334155;
                --input-bg: #0f172a;
                --success: #34d399;
                --shadow: 0 10px 15px -3px rgb(0 0 0 / 0.5);
            }

            * { box-sizing: border-box; margin: 0; padding: 0; transition: background-color 0.3s, color 0.3s; }
            
            body {
                font-family: 'Plus Jakarta Sans', sans-serif;
                background-color: var(--bg-body);
                color: var(--text-main);
                min-height: 100vh;
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                padding: 1rem;
            }

            /* Navbar */
            .navbar {
                width: 100%; max-width: 600px; display: flex;
                justify-content: space-between; align-items: center; margin-bottom: 2rem;
            }
            .brand { font-size: 1.5rem; font-weight: 800; display: flex; align-items: center; gap: 0.5rem; }
            .brand span { color: var(--primary); }
            .theme-toggle { background: none; border: none; cursor: pointer; font-size: 1.2rem; padding: 8px; border-radius: 50%; background-color: var(--bg-card); border: 1px solid var(--border); }

            /* Card */
            .container {
                background: var(--bg-card); width: 100%; max-width: 500px;
                border-radius: 24px; box-shadow: var(--shadow);
                border: 1px solid var(--border); padding: 2rem;
            }

            /* Password Display */
            .password-box {
                background: var(--input-bg);
                border-radius: 12px;
                padding: 1.5rem;
                margin-bottom: 2rem;
                position: relative;
                border: 1px solid var(--border);
                display: flex; align-items: center; justify-content: space-between;
            }
            .password-text {
                font-family: 'JetBrains Mono', monospace;
                font-size: 1.5rem;
                word-break: break-all;
                color: var(--text-main);
                font-weight: 500;
            }
            .copy-btn {
                background: var(--bg-card);
                border: 1px solid var(--border);
                border-radius: 8px;
                padding: 0.5rem;
                cursor: pointer;
                color: var(--text-sub);
                transition: all 0.2s;
                margin-left: 1rem; flex-shrink: 0;
            }
            .copy-btn:hover { border-color: var(--primary); color: var(--primary); }
            .copy-btn.copied { background-color: var(--success); color: white; border-color: var(--success); }

            /* Controls */
            .controls { display: grid; gap: 1rem; }
            
            .range-group { margin-bottom: 1rem; }
            .range-header { display: flex; justify-content: space-between; margin-bottom: 0.5rem; font-weight: 600; font-size: 0.9rem; }
            input[type="range"] { width: 100%; cursor: pointer; accent-color: var(--primary); }

            .options-grid {
                display: grid; grid-template-columns: 1fr 1fr; gap: 0.8rem;
            }
            .checkbox-wrapper {
                display: flex; align-items: center; gap: 0.5rem;
                font-size: 0.9rem; color: var(--text-sub);
                cursor: pointer;
            }
            input[type="checkbox"] { width: 1.2rem; height: 1.2rem; accent-color: var(--primary); cursor: pointer; }

            /* Action Button */
            .btn-generate {
                width: 100%;
                margin-top: 1.5rem;
                padding: 1rem;
                border-radius: 12px;
                background-color: var(--primary);
                color: white;
                font-weight: 700;
                font-size: 1rem;
                border: none;
                cursor: pointer;
                transition: transform 0.1s, background-color 0.2s;
                box-shadow: 0 4px 12px rgba(99, 102, 241, 0.3);
            }
            .btn-generate:hover { background-color: var(--primary-hover); transform: translateY(-2px); }
            .btn-generate:active { transform: scale(0.98); }

            /* Footer */
            .dev-footer {
                margin-top: 3rem; text-align: center; font-size: 0.9rem; color: var(--text-sub);
                padding: 1rem; width: 100%;
            }
            .dev-badge {
                display: inline-block; background: var(--bg-card); padding: 5px 15px;
                border-radius: 20px; border: 1px solid var(--border); font-weight: 500; margin-top: 5px;
            }
            .dev-name { color: var(--primary); font-weight: 700; }

            .strength-tag {
                font-size: 0.75rem; padding: 2px 8px; border-radius: 4px;
                background: #e2e8f0; color: #64748b; font-weight: 600; margin-top: 5px; display: inline-block;
            }
        </style>
    </head>
    <body>

        <nav class="navbar">
            <div class="brand">πŸ” password generator</div>
            <button class="theme-toggle" onclick="toggleTheme()" id="themeBtn">πŸŒ™</button>
        </nav>

        <div class="container">
            <div class="password-box">
                <div style="width: 100%;">
                    <div id="passwordResult" class="password-text">...</div>
                    <div id="strengthLabel" class="strength-tag">Strength: -</div>
                </div>
                <button class="copy-btn" id="copyBtn" onclick="copyPassword()" title="Copy to Clipboard">
                    πŸ“‹
                </button>
            </div>

            <div class="controls">
                
                <div class="range-group">
                    <div class="range-header">
                        <label>Password Length</label>
                        <span id="lengthVal" style="color: var(--primary);">16</span>
                    </div>
                    <input type="range" id="lengthInput" min="8" max="64" value="16" oninput="updateLength(this.value)">
                </div>

                <div class="options-grid">
                    <label class="checkbox-wrapper">
                        <input type="checkbox" id="chkUpper" checked> Uppercase (A-Z)
                    </label>
                    <label class="checkbox-wrapper">
                        <input type="checkbox" id="chkLower" checked> Lowercase (a-z)
                    </label>
                    <label class="checkbox-wrapper">
                        <input type="checkbox" id="chkNumbers" checked> Numbers (0-9)
                    </label>
                    <label class="checkbox-wrapper">
                        <input type="checkbox" id="chkSymbols" checked> Symbols (!@#)
                    </label>
                    <label class="checkbox-wrapper">
                        <input type="checkbox" id="chkAmbiguous"> Exclude Ambiguous
                    </label>
                </div>

                <button class="btn-generate" onclick="generate()">⚑ Generate Password</button>
            </div>
        </div>

        <footer class="dev-footer">
            <div>Designed & Developed by</div>
            <div class="dev-badge">
                <span class="dev-name">Sameer Banchhor</span> | Data Scientist
            </div>
        </footer>

        <script>
            // --- Theme Logic ---
            const html = document.documentElement;
            const themeBtn = document.getElementById('themeBtn');
            function toggleTheme() {
                const current = html.getAttribute('data-theme');
                const next = current === 'light' ? 'dark' : 'light';
                html.setAttribute('data-theme', next);
                themeBtn.textContent = next === 'light' ? 'πŸŒ™' : 'β˜€οΈ';
                localStorage.setItem('theme', next);
            }
            const savedTheme = localStorage.getItem('theme') || 'light';
            html.setAttribute('data-theme', savedTheme);
            themeBtn.textContent = savedTheme === 'light' ? 'πŸŒ™' : 'β˜€οΈ';

            // --- UI Logic ---
            function updateLength(val) {
                document.getElementById('lengthVal').textContent = val;
            }

            async function generate() {
                const length = document.getElementById('lengthInput').value;
                const upper = document.getElementById('chkUpper').checked;
                const lower = document.getElementById('chkLower').checked;
                const nums = document.getElementById('chkNumbers').checked;
                const syms = document.getElementById('chkSymbols').checked;
                const ambig = document.getElementById('chkAmbiguous').checked;

                // Validation
                if(!upper && !lower && !nums && !syms) {
                    alert("Please select at least one character type.");
                    return;
                }

                const params = new URLSearchParams({
                    length: length,
                    include_uppercase: upper,
                    include_lowercase: lower,
                    include_numbers: nums,
                    include_symbols: syms,
                    exclude_ambiguous: ambig
                });

                try {
                    const res = await fetch(`/security/generate-password?${params}`);
                    const data = await res.json();
                    
                    if(res.ok) {
                        const pwd = data.password;
                        const strength = data.strength;
                        
                        // Animate text change
                        const resultEl = document.getElementById('passwordResult');
                        resultEl.style.opacity = 0;
                        setTimeout(() => {
                            resultEl.textContent = pwd;
                            document.getElementById('strengthLabel').textContent = `Strength: ${strength}`;
                            updateStrengthColor(strength);
                            resultEl.style.opacity = 1;
                        }, 150);

                        // Reset copy button
                        const copyBtn = document.getElementById('copyBtn');
                        copyBtn.classList.remove('copied');
                        copyBtn.textContent = "πŸ“‹";
                    } else {
                        alert(data.detail || "Error generating password");
                    }
                } catch(e) {
                    console.error(e);
                    alert("Network error");
                }
            }

            function updateStrengthColor(strength) {
                const badge = document.getElementById('strengthLabel');
                let color = "#64748b";
                let bg = "#e2e8f0";
                
                if(strength === "Strong") { color = "#10b981"; bg = "#d1fae5"; }
                if(strength === "Very Strong") { color = "#6366f1"; bg = "#e0e7ff"; }
                if(strength === "Weak") { color = "#ef4444"; bg = "#fee2e2"; }

                badge.style.color = color;
                badge.style.backgroundColor = bg;
            }

            function copyPassword() {
                const text = document.getElementById('passwordResult').textContent;
                if(text === "...") return;

                navigator.clipboard.writeText(text).then(() => {
                    const btn = document.getElementById('copyBtn');
                    btn.classList.add('copied');
                    btn.textContent = "βœ…";
                    
                    setTimeout(() => {
                        btn.classList.remove('copied');
                        btn.textContent = "πŸ“‹";
                    }, 2000);
                });
            }

            // Generate one on load
            window.onload = generate;
        </script>
    </body>
    </html>
    """
    return html_content