#!/usr/bin/env python3
"""
╔══════════════════════════════════════════════════════════════╗
║          DARSHAN MISTARI — Terminal Portfolio v1.0           ║
║              Run: python3 portfolio.py                       ║
╚══════════════════════════════════════════════════════════════╝
"""

import os
import sys
import time
import shutil

# ─── ANSI Colors ───────────────────────────────────────────────
class C:
    GREEN       = '\033[92m'
    GREEN_DIM   = '\033[32m'
    CYAN        = '\033[96m'
    AMBER       = '\033[93m'
    RED         = '\033[91m'
    WHITE       = '\033[97m'
    DIM         = '\033[2m'
    BOLD        = '\033[1m'
    RESET       = '\033[0m'

def clr(color, text):
    return f"{color}{text}{C.RESET}"

# ─── Helpers ────────────────────────────────────────────────────
def clear():
    os.system('clear' if os.name == 'posix' else 'cls')

def width():
    return shutil.get_terminal_size((80, 24)).columns

def slow_print(text, delay=0.012):
    for ch in text:
        sys.stdout.write(ch)
        sys.stdout.flush()
        time.sleep(delay)
    print()

def print_line(char='─', color=C.DIM):
    print(clr(color, char * min(width(), 80)))

def section_header(title, cmd):
    print()
    print_line('─', C.GREEN_DIM)
    print(f"  {clr(C.GREEN, 'darshan')}@{clr(C.CYAN,'robotics')}:{clr(C.AMBER,'~')}$ {clr(C.DIM, cmd)}")
    print(f"  {clr(C.AMBER + C.BOLD, title)}")
    print_line('─', C.GREEN_DIM)

def bullet(text, color=C.WHITE):
    print(f"    {clr(C.GREEN, '▸')} {clr(color, text)}")

def tag_line(tags):
    row = "    "
    for t in tags:
        row += clr(C.CYAN, f"[{t}] ")
    print(row)

def pause():
    print()
    input(clr(C.DIM, "  ── press ENTER to continue ──"))

# ─── Boot sequence ───────────────────────────────────────────────
def boot_sequence():
    clear()
    msgs = [
        (C.DIM,   "[  0.001] Linux robotics-ws 6.5.0 #1 SMP"),
        (C.DIM,   "[  0.043] Loading ROS2 HUMBLE workspace...  "),
        (C.DIM,   "[  0.112] Initializing perception modules... "),
        (C.DIM,   "[  0.201] Mounting /dev/portfolio...         "),
        (C.GREEN, "[  0.320] System ready. All modules online.  "),
    ]
    for color, msg in msgs:
        if "..." in msg:
            sys.stdout.write(clr(color, msg))
            sys.stdout.flush()
            time.sleep(0.4)
            print(clr(C.GREEN, "OK"))
        else:
            slow_print(clr(color, msg), delay=0.008)
        time.sleep(0.15)
    time.sleep(0.3)
    clear()

# ─── ASCII Banner ────────────────────────────────────────────────
BANNER = r"""
  ██████╗  █████╗ ██████╗ ███████╗██╗  ██╗ █████╗ ███╗   ██╗
  ██╔══██╗██╔══██╗██╔══██╗██╔════╝██║  ██║██╔══██╗████╗  ██║
  ██║  ██║███████║██████╔╝███████╗███████║███████║██╔██╗ ██║
  ██║  ██║██╔══██║██╔══██╗╚════██║██╔══██║██╔══██║██║╚██╗██║
  ██████╔╝██║  ██║██║  ██║███████║██║  ██║██║  ██║██║ ╚████║
  ╚═════╝ ╚═╝  ╚═╝╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝╚═╝  ╚═╝╚═╝  ╚═══╝
"""

def show_header():
    print(clr(C.GREEN + C.BOLD, BANNER))
    print(clr(C.AMBER, "  ┌─── JUNIOR ROBOTICS SOFTWARE ENGINEER ──────────────────────────┐"))
    print(clr(C.AMBER, "  │") + clr(C.CYAN, "  📍 Pune, MH, India  |  🔗 linkedin.com/in/darshanxdevs/        ") + clr(C.AMBER, "│"))
    print(clr(C.AMBER, "  │") + clr(C.CYAN, "  📧 darshanmistari14@gmail.com  |  🌐 eyeofgod-two.vercel.app   ") + clr(C.AMBER, "│"))
    print(clr(C.AMBER, "  └─────────────────────────────────────────────────────────────────┘"))
    print()

# ─── Menu ────────────────────────────────────────────────────────
MENU = [
    ("1", about_fn   := None, "whoami --verbose",        "About Me"),
    ("2", None,               "cat experience.log",      "Experience"),
    ("3", None,               "ls -la projects/",        "Projects"),
    ("4", None,               "cat /proc/skills",        "Skills"),
    ("5", None,               "cat achievements.txt",    "Achievements"),
    ("6", None,               "dpkg -l | grep certs",    "Certifications"),
    ("q", None,               "exit 0",                  "Exit"),
]

MENU_ITEMS = [
    ("1", "whoami --verbose",        "About Me"),
    ("2", "cat experience.log",      "Experience"),
    ("3", "ls -la projects/",        "Projects"),
    ("4", "cat /proc/skills",        "Skills"),
    ("5", "cat achievements.txt",    "Achievements"),
    ("6", "dpkg -l | grep certs",    "Certifications"),
    ("q", "exit 0",                  "Exit"),
]

def show_menu():
    print(clr(C.GREEN_DIM, "  ┌─── COMMANDS ─────────────────────────────────────────┐"))
    for key, cmd, label in MENU_ITEMS:
        k = clr(C.GREEN + C.BOLD, f"  [{key}]")
        c = clr(C.DIM, f"  {cmd:<38}")
        print(f"{clr(C.GREEN_DIM,'  │')}{k}{c}{clr(C.WHITE, label)}")
    print(clr(C.GREEN_DIM, "  └───────────────────────────────────────────────────────┘"))
    print()

def main_screen():
    clear()
    show_header()
    show_menu()
    sys.stdout.write(f"  {clr(C.GREEN,'darshan')}@{clr(C.CYAN,'robotics')}:{clr(C.AMBER,'~')}$ ")
    sys.stdout.flush()

# ─── Sections ────────────────────────────────────────────────────
def about():
    section_header("ABOUT ME", "whoami --verbose")
    print()
    lines = [
        "Junior Robotics Software Engineer with hands-on experience in",
        "ROS/ROS2-based system development, module integration, and",
        "debugging in Linux environments.",
        "",
        "Strong foundation in C++ and Python with practical experience",
        "in system testing, sensor integration, and real-time robotics",
        "software validation.",
        "",
        "Goal: Building reliable, production-ready robotics systems",
        "through structured development and debugging practices.",
    ]
    for line in lines:
        slow_print(f"    {clr(C.WHITE, line)}", delay=0.008)

    print()
    print(f"    {clr(C.AMBER,'Education  :')} {clr(C.WHITE, 'Ajeenkya D Y Patil School of Engineering')}")
    print(f"    {clr(C.AMBER,'Degree     :')} {clr(C.WHITE, 'B.E. Robotics  (Aug 2023 – May 2027)')}")
    print(f"    {clr(C.AMBER,'Status     :')} {clr(C.GREEN,  '● Open to opportunities')}")
    pause()

def experience():
    section_header("EXPERIENCE", "cat experience.log")
    print()
    print(f"  {clr(C.GREEN + C.BOLD, '▶  Acceleration Robotics')}")
    print(f"     {clr(C.AMBER, 'Role  :')} {clr(C.WHITE, 'Machine Learning Intern (ROS)')}")
    print(f"     {clr(C.AMBER, 'Stack :')} {clr(C.CYAN,  'ROS2 · LiDAR · Camera · IMU · Python · Git')}")
    print()
    duties = [
        "Developed and debugged ROS/ROS2 nodes for perception modules",
        "Integrated sensor drivers (LiDAR, Camera, IMU) into robotics stack",
        "Performed runtime debugging using ROS CLI tools and log analysis",
        "Validated end-to-end data flow across multiple nodes",
        "Supported system testing under simulation and real-world conditions",
        "Used Git for version control and collaborative feature integration",
    ]
    for d in duties:
        bullet(d)
        time.sleep(0.05)
    pause()

def projects():
    section_header("PROJECTS", "ls -la projects/")

    print()
    print(f"  {clr(C.GREEN + C.BOLD, '▶  [SIH 2025] Autonomous LunarBot')}")
    print(f"     {clr(C.AMBER, 'Period :')} Aug 2023 – Present  |  Pune, MH")
    print(f"     {clr(C.RED + C.BOLD, '  ★  Smart India Hackathon — TOP 5 TEAMS NATIONWIDE')}")
    print()
    for p in [
        "Developed ROS2-based autonomy stack for quadruped rover & quadrotor",
        "Integrated LiDAR, Camera, and IMU drivers across sim and hardware",
        "Debugged ROS2 topic failures, transform mismatches, param config issues",
        "End-to-end system testing: latency analysis + localization validation",
        "Integrated perception outputs into navigation and control modules",
        "Conducted regression testing after feature updates",
    ]: bullet(p)
    tag_line(["ROS2", "C++", "Python", "OpenCV", "LiDAR", "IMU", "Linux"])

    print()
    print(f"  {clr(C.GREEN + C.BOLD, '▶  [eYantra IITB] Autonomous Warehouse Drone')}")
    print(f"     {clr(C.AMBER, 'Period :')} Jan 2024 – May 2024  |  Mumbai, MH")
    print(f"     {clr(C.RED + C.BOLD, '  ★  eYantra Robotics Competition — IIT Bombay Finalist')}")
    print()
    for p in [
        "Implemented ROS-based navigation and docking software",
        "Debugged node-level failures using structured log isolation",
        "Tuned system parameters for stable performance under compute limits",
        "Validated perception-to-control pipeline in indoor environment",
    ]: bullet(p)
    tag_line(["ROS", "MAVROS", "Python", "OpenCV", "Linux"])

    print()
    print(f"  {clr(C.GREEN + C.BOLD, '▶  ML & 3D ROS Perception Research')}")
    print(f"     {clr(C.AMBER, 'Type   :')} Self-Directed Research Practice")
    print()
    for p in [
        "Implemented YOLOv8, Segment Anything, DINO-style self-supervised pretraining",
        "Evaluated latency–accuracy trade-offs: CPU vs GPU deployment",
        "Documented experiments with clear metrics and reproducible results",
    ]: bullet(p)
    tag_line(["YOLOv8", "SAM", "DINO", "PyTorch", "Edge AI"])
    pause()

def skills():
    section_header("SKILLS", "cat /proc/skills")
    print()
    skill_data = [
        ("Core Languages",     ["Python", "C", "C++"]),
        ("Robotics & ROS2",    ["Nodes", "Topics", "Services", "Actions", "Launch Files", "MAVROS", "tf2"]),
        ("Navigation/SLAM",    ["Autonomous Navigation", "Basic SLAM", "Path Planning"]),
        ("Simulators",         ["Gazebo / Ignition", "NVIDIA Isaac Sim"]),
        ("Sensor Stack",       ["LiDAR", "Camera", "IMU", "Sensor Fusion", "UART", "CAN", "TCP/IP"]),
        ("Machine Learning",   ["Regression", "SVM", "Decision Trees", "Random Forest", "Gradient Boosting", "k-Means", "PCA"]),
        ("Deep Learning",      ["Basic CNNs", "Transfer Learning", "YOLOv8", "SAM", "DINO"]),
        ("ML Libraries",       ["PyTorch", "TensorFlow", "scikit-learn", "NumPy", "Pandas", "SciPy"]),
        ("Edge AI",            ["GPU Inference", "Model Optimization", "Latency–Accuracy Tradeoffs"]),
        ("Systems & DevOps",   ["Linux", "Git/GitHub", "Docker", "REST APIs", "SSH"]),
        ("Testing & QA",       ["System Testing", "Regression Testing", "RCA", "DFMEA", "Fishbone"]),
        ("MLOps",              ["Experiment Tracking", "Reproducibility", "Versioning"]),
    ]
    for cat, items in skill_data:
        cat_str = clr(C.AMBER, f"  {cat:<22}")
        items_str = clr(C.CYAN, " · ".join(items))
        print(f"{cat_str}{clr(C.GREEN_DIM, '│')}  {items_str}")
        time.sleep(0.04)
    pause()

def achievements():
    section_header("ACHIEVEMENTS", "cat achievements.txt")
    print()
    achs = [
        ("🏆", "WINNER",   "2 National Hackathons",                   "National-level competition victories"),
        ("🥇", "TOP 5",    "Smart India Hackathon 2025",               "Top 5 teams nationwide — Govt. of India"),
        ("🤖", "FINALIST", "eYantra Robotics 2024/2025 — IIT Bombay", "Autonomous warehouse drone project"),
        ("⭐", "FINALIST", "13 National-Level Competitions",           "Consistent top-tier performance"),
    ]
    for icon, badge, name, desc in achs:
        print(f"  {icon}  {clr(C.GREEN + C.BOLD, f'[{badge}]'):<30} {clr(C.WHITE, name)}")
        print(f"         {clr(C.DIM, desc)}")
        print()
        time.sleep(0.1)
    pause()

def certifications():
    section_header("CERTIFICATIONS", "dpkg -l | grep certs")
    print()
    certs = [
        ("Udemy",       "ROS 2 Advanced Course"),
        ("Stanford",    "Advanced Machine Learning"),
        ("Harkirat S.", "Full Stack & DevOps Cohort"),
        ("Self",        "Data Science / Deep Learning / ML / ROS2 (Research Papers & Docs)"),
    ]
    for src, name in certs:
        print(f"  {clr(C.AMBER, f'[{src:<12}]')}  {clr(C.WHITE, name)}")
        time.sleep(0.1)
    pause()

# ─── Main Loop ───────────────────────────────────────────────────
ACTIONS = {
    "1": about,
    "2": experience,
    "3": projects,
    "4": skills,
    "5": achievements,
    "6": certifications,
}

def run():
    boot_sequence()
    while True:
        main_screen()
        try:
            choice = input().strip().lower()
        except (KeyboardInterrupt, EOFError):
            choice = "q"

        if choice == "q":
            clear()
            print()
            slow_print(clr(C.GREEN, "  Logging out of darshan@robotics..."), 0.02)
            time.sleep(0.3)
            slow_print(clr(C.DIM,   "  Connection closed. Goodbye!"), 0.02)
            print()
            sys.exit(0)
        elif choice in ACTIONS:
            clear()
            ACTIONS[choice]()
        else:
            print(clr(C.RED, f"\n  bash: '{choice}': command not found\n"))
            time.sleep(0.8)

if __name__ == "__main__":
    if not sys.stdout.isatty():
        # Still run even if not tty (e.g. some terminal emulators)
        pass
    run()
