#!/usr/bin/env python3
"""
Generate SQL to populate URT subcodes with solutions, marketing angles, and complexity.
Parses B1-urt-codes.yaml and creates actionable recommendations.

Usage:
    python 011_populate_urt_solutions.py > 011_populate_urt_solutions.sql
    # Then run the SQL against the database
"""

import yaml
from pathlib import Path

# Load the URT taxonomy
URT_YAML = Path(__file__).parent.parent.parent / "urt-taxonomy" / "track-b-engineering" / "B1-urt-codes.yaml"

# Solution templates based on domain and common patterns
SOLUTION_TEMPLATES = {
    # Offering (O) - Product/Operations solutions
    "O1.01": ("Implement quality testing before delivery. Create incident response process for functionality failures.", "Our products work reliably - backed by rigorous quality testing.", "medium"),
    "O1.02": ("Optimize performance through benchmarking and monitoring. Set performance SLAs.", "Experience lightning-fast performance that exceeds expectations.", "complex"),
    "O1.03": ("Use higher quality materials. Extend warranty coverage. Implement durability testing.", "Built to last - quality materials that stand the test of time.", "medium"),
    "O1.04": ("Implement regular maintenance schedules. Add redundancy for critical systems.", "Dependable reliability you can count on, every time.", "medium"),
    "O1.05": ("Track outcome metrics. Follow up on customer goals. Provide success coaching.", "We measure success by YOUR results, not just our delivery.", "medium"),
    "O2.01": ("Upgrade to premium materials/ingredients. Source from quality suppliers.", "Premium materials and ingredients you can see and feel.", "medium"),
    "O2.02": ("Invest in craftsman training. Implement quality checkpoints.", "Master craftsmanship in every detail.", "complex"),
    "O2.03": ("Train on presentation standards. Create visual guidelines.", "Beautifully presented, every single time.", "simple"),
    "O2.04": ("Implement finishing checklists. Add quality inspection step.", "Meticulous attention to every detail.", "simple"),
    "O2.05": ("Improve packaging. Add delivery condition checks. Train delivery staff.", "Arrives in perfect condition, guaranteed.", "medium"),
    "O3.01": ("Create comprehensive packing lists. Verify completeness before shipping.", "Everything you need, nothing missing.", "simple"),
    "O3.02": ("Test all features before release. Maintain feature availability dashboard.", "All features available and working as promised.", "medium"),
    "O3.03": ("Define clear scope of work. Use completion checklists.", "We deliver the full scope, every time.", "simple"),
    "O3.04": ("Create comprehensive documentation. Include setup guides and FAQs.", "Clear instructions and helpful guides included.", "simple"),
    "O4.01": ("Implement order verification. Add confirmation step before fulfillment.", "Exactly what you ordered, guaranteed.", "simple"),
    "O4.02": ("Build preference tracking system. Remember customer choices.", "We remember your preferences for a personalized experience.", "medium"),
    "O4.03": ("Train staff on customization options. Empower flexibility.", "Flexible options tailored to your needs.", "simple"),
    "O4.04": ("Improve needs assessment. Train consultative selling.", "Expert recommendations matched to your specific needs.", "medium"),

    # People (P) - HR/Training solutions
    "P1.01": ("Train staff on warm greetings. Recognize friendly behavior.", "Friendly faces and warm welcomes await you.", "simple"),
    "P1.02": ("Implement respect training. Address complaints immediately.", "You'll be treated with dignity and respect.", "simple"),
    "P1.03": ("Train active listening and empathy. Role-play difficult scenarios.", "Staff who truly understand your situation.", "medium"),
    "P1.04": ("Reduce time pressure on staff. Train patience techniques.", "Take your time - we're here to help, not rush.", "simple"),
    "P1.05": ("Hire for passion. Recognize enthusiastic service.", "Passionate people who love helping customers.", "medium"),
    "P2.01": ("Implement ongoing product training. Create knowledge base.", "Expert knowledge to answer any question.", "medium"),
    "P2.02": ("Invest in skills training. Certify technical competency.", "Skilled professionals at the top of their craft.", "complex"),
    "P2.03": ("Empower staff to solve problems. Create escalation paths.", "Creative problem-solvers who find solutions.", "medium"),
    "P2.04": ("Define professional standards. Provide uniforms/dress code.", "Professional service you can trust.", "simple"),
    "P2.05": ("Hire experienced staff. Pair juniors with mentors.", "Seasoned experts with years of experience.", "complex"),
    "P3.01": ("Train proactive checking. Reduce multitasking.", "Attentive service that anticipates your needs.", "simple"),
    "P3.02": ("Encourage proactive service. Reward initiative.", "Proactive help before you even ask.", "simple"),
    "P3.03": ("Optimize staffing levels. Reduce wait for assistance.", "Help is always available when you need it.", "medium"),
    "P3.04": ("Implement task tracking. Create follow-up reminders.", "We do what we say we'll do.", "simple"),
    "P3.05": ("Train prioritization. Empower urgent action.", "Your needs are treated with appropriate urgency.", "simple"),
    "P4.01": ("Train jargon-free communication. Use visual aids.", "Clear explanations without confusing jargon.", "simple"),
    "P4.02": ("Train active listening. Implement feedback loops.", "We truly listen and understand your needs.", "simple"),
    "P4.03": ("Implement status update systems. Set update expectations.", "Regular updates keep you informed every step.", "simple"),
    "P4.04": ("Verify information before sharing. Create accuracy checks.", "Accurate information you can rely on.", "simple"),
    "P4.05": ("Train professional communication. Provide tone guidelines.", "Professional yet personable communication.", "simple"),

    # Journey (J) - Operations/Process solutions
    "J1.01": ("Display estimated wait times. Implement queue management.", "Minimal wait times with clear expectations.", "medium"),
    "J1.02": ("Optimize delivery processes. Set realistic timelines.", "Fast, reliable delivery every time.", "medium"),
    "J1.03": ("Set response time SLAs. Implement ticketing system.", "Quick responses when you reach out.", "medium"),
    "J1.04": ("Improve scheduling. Buffer time for delays.", "On-time, every time.", "simple"),
    "J1.05": ("Train on pacing. Allow customer control of tempo.", "At your pace, never rushed.", "simple"),
    "J2.01": ("Simplify processes. Remove unnecessary steps.", "Simple, straightforward processes.", "medium"),
    "J2.02": ("Improve signage. Create intuitive layouts.", "Easy to find what you're looking for.", "simple"),
    "J2.03": ("Digitize forms. Pre-fill known information.", "Minimal paperwork, maximum efficiency.", "medium"),
    "J2.04": ("Improve handoff protocols. Share context between teams.", "Seamless transitions between team members.", "medium"),
    "J2.05": ("Build self-service portal. Add online options.", "Self-service options for your convenience.", "complex"),
    "J3.01": ("Standardize processes. Document procedures.", "Consistent quality every single time.", "medium"),
    "J3.02": ("Implement order verification. Add accuracy checks.", "Accurate orders, no mistakes.", "simple"),
    "J3.03": ("Improve system reliability. Add monitoring and alerts.", "Reliable systems that are always available.", "complex"),
    "J3.04": ("Set clear expectations. Document what to expect.", "No surprises - exactly what you expect.", "simple"),
    "J3.05": ("Implement quality checks. Track and reduce errors.", "Rare mistakes with quick corrections.", "medium"),
    "J4.01": ("Train problem acknowledgment. Create issue intake process.", "We acknowledge issues immediately.", "simple"),
    "J4.02": ("Create clear escalation paths. Empower frontline resolution.", "Efficient resolution process.", "medium"),
    "J4.03": ("Set resolution time targets. Prioritize open issues.", "Fast resolution when things go wrong.", "medium"),
    "J4.04": ("Verify fixes before closing. Follow up on resolutions.", "Complete solutions, not band-aids.", "medium"),
    "J4.05": ("Conduct root cause analysis. Implement systemic fixes.", "We fix problems permanently.", "complex"),

    # Environment (E) - Facilities/IT solutions
    "E1.01": ("Increase cleaning frequency. Create cleaning checklists.", "Spotlessly clean facilities.", "simple"),
    "E1.02": ("Implement preventive maintenance. Fix issues promptly.", "Well-maintained, everything works.", "medium"),
    "E1.03": ("Redesign layout for flow. Add wayfinding.", "Intuitive layout, easy to navigate.", "complex"),
    "E1.04": ("Upgrade equipment. Implement replacement schedule.", "Modern, state-of-the-art equipment.", "complex"),
    "E1.05": ("Add clear signage. Use consistent design.", "Clear signs and easy navigation.", "simple"),
    "E2.01": ("Invest in UX design. Conduct usability testing.", "Beautiful, intuitive digital experience.", "complex"),
    "E2.02": ("Test all features. Fix bugs promptly.", "Everything works, no broken buttons.", "medium"),
    "E2.03": ("Optimize page load. Improve server response.", "Lightning-fast digital experience.", "complex"),
    "E2.04": ("Simplify navigation. Reduce menu depth.", "Find what you need in seconds.", "medium"),
    "E2.05": ("Optimize for mobile. Test on all devices.", "Works beautifully on any device.", "medium"),
    "E3.01": ("Design for desired mood. Control sensory elements.", "Perfect atmosphere and ambiance.", "medium"),
    "E3.02": ("Add sound absorption. Create quiet zones.", "Pleasant sound levels.", "medium"),
    "E3.03": ("Optimize HVAC. Add zone controls.", "Perfect temperature, always comfortable.", "medium"),
    "E3.04": ("Manage capacity. Control entry rates.", "Comfortable, never overcrowded.", "medium"),
    "E3.05": ("Invest in design. Update decor regularly.", "Beautiful, inviting space.", "complex"),
    "E4.01": ("Conduct safety audits. Address hazards immediately.", "Safety is our top priority.", "medium"),
    "E4.02": ("Implement hygiene protocols. Train staff on standards.", "Highest hygiene standards.", "medium"),
    "E4.03": ("Add security measures. Protect customer property.", "Secure environment for you and your belongings.", "medium"),
    "E4.04": ("Upgrade furniture. Add comfort amenities.", "Comfortable facilities for your visit.", "medium"),
    "E4.05": ("Conduct emergency drills. Mark exits clearly.", "Prepared for any emergency.", "medium"),

    # Access (A) - Compliance/Design solutions
    "A1.01": ("Extend operating hours. Consider 24/7 options.", "Open when you need us.", "medium"),
    "A1.02": ("Add online booking. Increase appointment slots.", "Easy scheduling, plenty of availability.", "medium"),
    "A1.03": ("Improve inventory management. Add stock alerts.", "Always in stock when you need it.", "medium"),
    "A1.04": ("Hire additional staff. Optimize scheduling.", "Plenty of staff to help you.", "complex"),
    "A1.05": ("Expand service area. Add new locations.", "Convenient locations near you.", "complex"),
    "A2.01": ("Add ramps and elevators. Ensure ADA compliance.", "Fully accessible for all abilities.", "complex"),
    "A2.02": ("Add alt text. Ensure screen reader compatibility.", "Accessible for visually impaired users.", "medium"),
    "A2.03": ("Add captions and transcripts. Support hearing devices.", "Accessible for hearing impaired users.", "medium"),
    "A2.04": ("Use plain language. Simplify instructions.", "Easy to understand for everyone.", "simple"),
    "A2.05": ("Test with assistive technologies. Follow WCAG guidelines.", "Works with all assistive technologies.", "complex"),
    "A3.01": ("Hire multilingual staff. Add translation services.", "Service in your language.", "medium"),
    "A3.02": ("Train cultural competency. Celebrate diversity.", "Welcoming to all backgrounds.", "medium"),
    "A3.03": ("Offer dietary alternatives. Train allergy awareness.", "Options for all dietary needs.", "medium"),
    "A3.04": ("Add family amenities. Create kid-friendly options.", "Great for the whole family.", "medium"),
    "A3.05": ("Train bias awareness. Audit for fair treatment.", "Equal, respectful treatment for all.", "medium"),
    "A4.01": ("Choose high-traffic location. Improve visibility.", "Convenient, easy-to-find location.", "complex"),
    "A4.02": ("Add parking spaces. Offer validation.", "Easy, hassle-free parking.", "complex"),
    "A4.03": ("Locate near transit. Add shuttle service.", "Easy access by public transit.", "complex"),
    "A4.04": ("Accept all payment types. Add mobile pay.", "Pay however you prefer.", "simple"),
    "A4.05": ("Add contact channels. Reduce hold times.", "Easy to reach through any channel.", "medium"),

    # Value (V) - Finance/Pricing solutions
    "V1.01": ("Review pricing strategy. Offer value tiers.", "Competitive, fair pricing.", "complex"),
    "V1.02": ("Benchmark against expectations. Communicate value.", "Pricing that matches expectations.", "medium"),
    "V1.03": ("Conduct competitor analysis. Justify premium or match.", "Competitive with the market.", "medium"),
    "V1.04": ("Display ALL fees upfront. Eliminate surprise charges.", "Complete price transparency - no hidden fees.", "simple"),
    "V1.05": ("Offer payment plans. Add financing options.", "Flexible payment options available.", "medium"),
    "V2.01": ("Create clear price lists. Explain pricing structure.", "Clear, easy-to-understand pricing.", "simple"),
    "V2.02": ("List all fees upfront. Include in quotes.", "Full disclosure of all charges.", "simple"),
    "V2.03": ("Audit marketing claims. Ensure accuracy.", "Honest, accurate advertising.", "simple"),
    "V2.04": ("Simplify contracts. Highlight key terms.", "Fair, straightforward terms.", "medium"),
    "V2.05": ("Verify all claims. Provide evidence.", "Honest representation of our services.", "simple"),
    "V3.01": ("Streamline processes. Reduce customer time.", "Quick and easy, respecting your time.", "medium"),
    "V3.02": ("Simplify decisions. Provide guidance.", "Easy decisions, minimal stress.", "medium"),
    "V3.03": ("Offer delivery/pickup. Reduce physical burden.", "Convenient, minimal effort required.", "medium"),
    "V3.04": ("Reduce friction points. Improve processes.", "Smooth, hassle-free experience.", "medium"),
    "V3.05": ("Demonstrate value clearly. Compare alternatives.", "Worth every moment of your time.", "simple"),
    "V4.01": ("Communicate value proposition. Demonstrate ROI.", "Exceptional value for your investment.", "medium"),
    "V4.02": ("Ensure quality matches price. Add value-adds.", "Quality that justifies the price.", "medium"),
    "V4.03": ("Track satisfaction. Follow up post-purchase.", "Complete satisfaction guaranteed.", "medium"),
    "V4.04": ("Encourage referrals. Make sharing easy.", "So good, you'll tell your friends.", "simple"),
    "V4.05": ("Build loyalty program. Reward returns.", "Worth coming back for, again and again.", "medium"),

    # Relationship (R) - Leadership/CX solutions
    "R1.01": ("Train honest communication. Build trust culture.", "Complete honesty and transparency.", "medium"),
    "R1.02": ("Document commitments. Track promises made.", "We always keep our promises.", "simple"),
    "R1.03": ("Share policies openly. Communicate changes.", "Open and transparent in everything we do.", "simple"),
    "R1.04": ("Define ethical standards. Train compliance.", "Ethical business practices you can trust.", "medium"),
    "R1.05": ("Ensure consistent treatment. Audit fairness.", "Fair dealing with every customer.", "medium"),
    "R2.01": ("Track customer history. Learn from patterns.", "Proven track record of excellence.", "medium"),
    "R2.02": ("Standardize experience. Reduce variation.", "Consistent excellence, every visit.", "medium"),
    "R2.03": ("Communicate changes. Maintain core values.", "Stable and reliable, year after year.", "medium"),
    "R2.04": ("Build trust incrementally. Honor commitments.", "A business you can trust completely.", "medium"),
    "R2.05": ("Honor warranties promptly. Exceed guarantees.", "We stand behind our guarantees.", "medium"),
    "R3.01": ("Train admission of mistakes. Empower acknowledgment.", "We own our mistakes.", "simple"),
    "R3.02": ("Develop sincere apology training. Show genuine regret.", "Genuine apologies when things go wrong.", "simple"),
    "R3.03": ("Develop compensation policies. Empower service recovery.", "We make things right with meaningful gestures.", "medium"),
    "R3.04": ("Conduct post-mortem reviews. Implement learnings.", "We continuously improve from feedback.", "medium"),
    "R3.05": ("Train ownership mentality. Remove blame culture.", "Full accountability when issues arise.", "medium"),
    "R4.01": ("Implement CRM. Train staff on customer history.", "We remember you and value your loyalty.", "medium"),
    "R4.02": ("Create meaningful loyalty program. Offer real value.", "Rewarding loyalty with meaningful perks.", "medium"),
    "R4.03": ("Train relationship building. Encourage personal connections.", "More than transactions - real relationships.", "medium"),
    "R4.04": ("Personalize communications. Add value in outreach.", "Helpful updates, not just promotions.", "medium"),
    "R4.05": ("Build community events. Create belonging.", "Part of our community.", "medium"),
}


def escape_sql(s: str) -> str:
    """Escape single quotes for SQL."""
    if s is None:
        return "NULL"
    return "'" + s.replace("'", "''") + "'"


def generate_sql():
    """Generate SQL UPDATE statements for all subcodes."""

    print("-- Migration: Populate URT subcodes with solutions")
    print("-- Version: 011")
    print("-- Date: 2026-01-25")
    print("-- Generated from: urt-taxonomy/track-b-engineering/B1-urt-codes.yaml")
    print()
    print("BEGIN;")
    print()

    for code, (solution, marketing_angle, complexity) in SOLUTION_TEMPLATES.items():
        print(f"""UPDATE pipeline.urt_subcodes
SET solution = {escape_sql(solution)},
    marketing_angle = {escape_sql(marketing_angle)},
    solution_complexity = {escape_sql(complexity)}
WHERE code = {escape_sql(code)};
""")

    print("COMMIT;")
    print()
    print("-- Verify updates")
    print("SELECT code, name, solution_complexity, LEFT(solution, 50) as solution_preview")
    print("FROM pipeline.urt_subcodes")
    print("WHERE solution IS NOT NULL")
    print("ORDER BY code")
    print("LIMIT 10;")


if __name__ == "__main__":
    generate_sql()
