# app/contract_generator.py
from jinja2 import Template
from datetime import datetime
import os


class ContractGenerator:

    def __init__(self):
        self.contract_template = """
<!DOCTYPE html>
<html>
<head>
    <title>Independent Contractor Agreement - RateRight</title>
    <style>
        body { 
            font-family: Georgia, serif; 
            margin: 40px; 
            line-height: 1.6; 
            background: #fff;
        }
        .legal-content {
            background: #fff;
            border-radius: 8px;
            padding: 1.5rem;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            max-width: 100%;
        }
        h1 { 
            color: #2c3e50; 
            border-bottom: 2px solid #3498db; 
            padding-bottom: 10px;
            font-size: 1.5rem;
        }
        h2 { 
            color: #2c3e50;
            border-bottom: 2px solid #3498db;
            padding-bottom: 0.5rem;
            margin-top: 2rem;
            margin-bottom: 1rem;
            font-size: 1.4rem;
        }
        h3 {
            color: #34495e;
            margin-top: 1.5rem;
            margin-bottom: 0.75rem;
            font-size: 1.1rem;
        }
        .scope {
            background: #f8f9fa;
            padding: 15px;
            border-left: 4px solid #3498db;
            margin: 20px 0;
        }
        .parties { 
            background: #f8f9fa; 
            padding: 15px; 
            border-left: 4px solid #3498db; 
            margin: 20px 0; 
        }
        .highlight { 
            background: #fff3cd; 
            padding: 10px; 
            border: 1px solid #ffeaa7;
            margin: 10px 0;
        }
        .signature { 
            margin-top: 40px; 
            border-top: 1px solid #ddd; 
            padding-top: 20px; 
        }
        ul {
            padding-left: 1.5rem;
            margin-bottom: 1rem;
        }
        ul li {
            margin-bottom: 0.5rem;
        }
        .template-notice {
            background: rgba(255, 193, 7, 0.1);
            padding: 10px;
            border: 1px solid #ffeaa7;
            border-radius: 4px;
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <div class="legal-content">
        <h1>Independent Contractor Agreement</h1>

        <div class="scope">
            <h3>Scope of Document</h3>
            <p>This agreement governs independent contractor arrangements facilitated through the RateRight Platform. It complies with the Independent Contractors Act 2006 (Cth), Fair Work Act 2009 (Cth) (including the August 2024 amendments), and the Work Health and Safety Act 2011 (NSW). RateRight acts solely as a facilitator and is not a party to this agreement.</p>
            <p><strong>Date:</strong> {{ date }} | <strong>Version:</strong> v03 | <strong>Contract ID:</strong> RR-{{ contract_id }}</p>
        </div>

        <h3>Between:</h3>
        <div class="parties">
            <p><strong>{{ hirer_name }}</strong> ("Hirer"), ABN {{ hirer_abn }}<br>
            <strong>And:</strong><br>
            <strong>{{ contractor_name }}</strong> ("Worker"), ABN {{ contractor_abn }}</p>
            <p><strong>Facilitated by:</strong> RateRight Pty Ltd (ABN 46 689 397 582) – <em>Not a Party</em></p>
        </div>

        <h2>1. Job</h2>
        <p>The Worker agrees to provide <strong>{{ job_title }}</strong>: {{ job_description }}</p>
        <ul>
            <li><strong>Site:</strong> {{ job_location }}</li>
            <li><strong>Method:</strong> Worker chooses how to perform work, using own tools and skills</li>
            <li><strong>Changes:</strong> Only by written agreement between Hirer and Worker, including adjustments to pay if required</li>
        </ul>

        <h2>2. Independent Status</h2>
        <ul>
            <li>Worker operates as an independent contractor under the Fair Work Act multi-factor test</li>
            <li>No exclusivity, no direction of work methods, no integration into Hirer's business</li>
            <li>Worker responsible for tax, GST, superannuation, and business costs</li>
        </ul>

        <h2>3. Payment</h2>
        <ul>
            <li><strong>Agreed fee:</strong> ${{ hourly_rate }} per hour ({{ gst_note }})</li>
            <li>Paid via RateRight escrow system</li>
            <li>Worker receives 90.1% of fee after release (job amount minus 9.9% total deductions: 7% platform fee + 2.9% Stripe processing fee)</li>
            <li>Hirer pays the agreed job amount in full; no additional hidden fees</li>
        </ul>

        <h2>4. Safety</h2>
        <div class="highlight">
            <ul>
                <li><strong>Worker:</strong> Comply with the WHS Act 2011 (NSW), maintain valid licences, and hold insurance (minimum {{ insurance_amount }} public liability)</li>
                <li><strong>Hirer:</strong> Provide a safe workplace and ensure site compliance</li>
                <li><strong>White Card:</strong> {{ white_card_required }}</li>
                <li><strong>Safety Controls:</strong> {{ safety_controls }}</li>
                <li><strong>Risk Level:</strong> {{ risk_level }}</li>
            </ul>
        </div>

        <h2>4A. Trade-Specific Licensing & Compliance</h2>
        <ul>
            <li>Workers must hold all licences required by law for their trade (e.g., NSW Electrical Contractor Licence for electrical work, Plumbing Licence for plumbing, White Card for general construction)</li>
            <li>Workers must comply with all trade-specific Australian Standards applicable to their work (e.g., AS/NZS 3000 for electrical, AS/NZS 3500 for plumbing)</li>
            <li>Workers must maintain public liability insurance at the minimum level required by their trade risk category (low: $1m, medium: $2m, high: $5m, extreme: $10m)</li>
            <li>Hirers are responsible for verifying relevant licences and ensuring site safety conditions before work commences</li>
        </ul>

        <h2>5. Disputes</h2>
        <ul>
            <li>Parties must first attempt direct resolution</li>
            <li>If unresolved, escalate to RateRight facilitation, then external bodies (e.g., Fair Work Commission, SafeWork NSW)</li>
            <li>Governing law: NSW, Australia</li>
        </ul>

        <h2>6. Limits</h2>
        <ul>
            <li>Services provided "as is"</li>
            <li>Each party indemnifies the other (and RateRight) against claims arising from breaches, safety issues, or disputes</li>
        </ul>

        <h2>7. Intellectual Property & Confidentiality</h2>
        <ul>
            <li>IP in deliverables transfers to Hirer upon full payment</li>
            <li>Both parties must keep confidential information private unless agreed otherwise</li>
        </ul>

        <h2>8. Termination</h2>
        <p>Either party may terminate by mutual agreement or for breach (7 days' notice).</p>
        
        <h3>Payment on Termination:</h3>
        <ul>
            <li>No payment for incomplete work if Worker defaults</li>
            <li>Prorated payment for partial work if Hirer terminates without Worker fault</li>
        </ul>

        <div class="signature">
            <h2>Signatures</h2>
            <p><strong>Hirer:</strong> {{ hirer_signature_date or "Pending Digital Acceptance" }}</p>
            <p><strong>Worker:</strong> {{ contractor_signature_date or "Pending Digital Acceptance" }}</p>
        </div>

        <div class="template-notice">
            <p><strong>Generated by RateRight Platform:</strong> This contract is legally binding when both parties digitally accept. RateRight Pty Ltd acts solely as a facilitator and is not a party to this agreement.</p>
        </div>
    </div>
</body>
</html>
        """

    def generate_contract_data(self, job, hirer, worker, application):
        """Generate contract data from job and user info"""

        # Determine insurance amount based on risk
        insurance_amounts = {
            'low': '$1,000,000',
            'medium': '$2,000,000',
            'high': '$5,000,000',
            'extreme': '$10,000,000'
        }

        risk_level = getattr(job.category,
                             'whs_risk_level', 'medium') if hasattr(
                                 job, 'category') else 'medium'

        return {
            'date':
            datetime.now().strftime('%d %B %Y'),
            'job_title':
            job.title,
            'job_description':
            job.description,
            'job_location':
            job.location,
            'hourly_rate':
            f'{job.hourly_rate:.2f}',
            'gst_note':
            'plus GST if applicable',

            # Parties
            'hirer_name':
            f'{hirer.first_name} {hirer.last_name}',
            'hirer_abn':
            hirer.abn_number or 'Pending',
            'contractor_name':
            f'{worker.first_name} {worker.last_name}',
            'contractor_abn':
            worker.abn_number or 'Pending',

            # Risk and safety
            'risk_level':
            risk_level.upper(),
            'insurance_amount':
            insurance_amounts.get(risk_level.lower(), '$2,000,000'),
            'white_card_required':
            'Required' if job.white_card_required else 'Not Required',
            'safety_controls':
            self._get_safety_controls(risk_level),

            # Signatures (will be filled when signed)
            'hirer_signature_date':
            'Pending',
            'contractor_signature_date':
            'Pending',
            'contract_id':
            f'{job.id}-{application.id}-{datetime.now().strftime("%Y%m%d")}'
        }

    def _get_safety_controls(self, risk_level):
        """Get safety controls based on risk level"""
        controls = {
            'low':
            'Basic PPE, site induction',
            'medium':
            'PPE, SWMS review, toolbox talks',
            'high':
            'Full SWMS, licensing verification, daily briefings',
            'extreme':
            'SafeWork NSW notification, specialist licensing, continuous monitoring'
        }
        return controls.get(risk_level.lower(), 'Standard safety protocols')

    def render_contract_html(self, contract_data):
        """Render contract as HTML"""
        template = Template(self.contract_template)
        return template.render(**contract_data)

    def save_contract_html(self, contract_data, filename):
        """Save contract as HTML file"""
        html_content = self.render_contract_html(contract_data)

        # Create contracts directory if it doesn't exist
        os.makedirs('contracts', exist_ok=True)

        filepath = f'contracts/{filename}'
        with open(filepath, 'w', encoding='utf-8') as f:
            f.write(html_content)

        return filepath


# Test function
def test_contract_generation():
    """Test the contract generator with dummy data"""

    class DummyJob:

        def __init__(self):
            self.id = 1
            self.title = "Formwork Installation"
            self.description = "Install formwork for concrete slab, 3 days work"
            self.location = "Parramatta, NSW"
            self.hourly_rate = 45.00
            self.white_card_required = True

    class DummyUser:

        def __init__(self, name, abn):
            self.first_name = name.split()[0]
            self.last_name = name.split()[1] if len(name.split()) > 1 else ""
            self.abn_number = abn

    class DummyApplication:

        def __init__(self):
            self.id = 123

    # Create test data
    job = DummyJob()
    hirer = DummyUser("John Smith", "12 345 678 901")
    worker = DummyUser("Mike Johnson", "98 765 432 109")
    application = DummyApplication()

    # Generate contract
    generator = ContractGenerator()
    contract_data = generator.generate_contract_data(job, hirer, worker,
                                                     application)

    # Save as HTML
    filename = f"test_contract_{datetime.now().strftime('%Y%m%d_%H%M%S')}.html"
    filepath = generator.save_contract_html(contract_data, filename)

    print(f"✅ Test contract generated: {filepath}")
    print(f"📄 Contract ID: {contract_data['contract_id']}")

    return filepath


def test_with_real_jobs():
    """Test contract generation with real jobs from your database"""
    from app import create_app
    from app.models import Job, User, Category

    app = create_app()
    with app.app_context():
        # Get real jobs from your database
        jobs = Job.query.all()
        users = User.query.all()

        print(f"📊 Found {len(jobs)} jobs and {len(users)} users in database")

        if not jobs:
            print("❌ No jobs found! Create some test jobs first.")
            return

        if len(users) < 2:
            print("❌ Need at least 2 users (contractor + worker)")
            return

        # Use first job and first two users
        job = jobs[0]
        contractor = users[0]  # Assume first user is contractor
        worker = users[1] if len(users) > 1 else users[0]  # Second user is worker

        print(f"🏗️  Testing with real job: {job.title}")
        print(f"👔 Contractor: {contractor.first_name} {contractor.last_name}")
        print(f"👷 Worker: {worker.first_name} {worker.last_name}")

        # Create dummy application
        class DummyApplication:

            def __init__(self):
                self.id = 999

        application = DummyApplication()

        # Generate contract with REAL data
        generator = ContractGenerator()

        try:
            contract_data = generator.generate_contract_data(job, contractor,
                                                             worker, application)

            filename = f"real_job_contract_{job.id}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.html"
            filepath = generator.save_contract_html(contract_data, filename)

            print(f"✅ REAL CONTRACT GENERATED: {filepath}")
            print(f"📄 Contract ID: {contract_data['contract_id']}")
            print(f"💰 Hourly Rate: ${contract_data['hourly_rate']}")
            print(f"📍 Location: {contract_data['job_location']}")

            return filepath

        except Exception as e:
            print(f"❌ Error generating contract: {e}")
            print("💡 Might need to add hourly_rate field to Job model")
            return None


def create_contract_for_real_application(job_id, worker_user_id):
    """Create contract when a real application is accepted"""
    from app import create_app
    from app.models import Job, User

    app = create_app()
    with app.app_context():
        # Get real database objects
        job = Job.query.get(job_id)
        contractor = User.query.get(job.contractor_id)
        worker = User.query.get(worker_user_id)

        if not all([job, contractor, worker]):
            print("❌ Missing required data")
            return None

        # Create application object
        class ApplicationData:

            def __init__(self, job_id, worker_id):
                self.id = f"{job_id}_{worker_id}_{int(datetime.now().timestamp())}"

        application = ApplicationData(job_id, worker_user_id)

        # Generate contract
        generator = ContractGenerator()
        contract_data = generator.generate_contract_data(job, contractor,
                                                             worker, application)

        filename = f"contract_job_{job_id}_worker_{worker_user_id}.html"
        filepath = generator.save_contract_html(contract_data, filename)

        print(f"✅ Contract created for job {job_id}: {filepath}")
        return filepath


def test_with_real_database():
    """Test using the same database as your Flask app (PostgreSQL)"""
    import sys
    import os
    
    # Add project root to path
    project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    sys.path.insert(0, project_root)
    
    try:
        from app import create_app
        from app.models import Job, User, Category
        from app.extensions import db
        
        app = create_app()
        
        with app.app_context():
            print(f"🗄️  Connected to: {app.config['SQLALCHEMY_DATABASE_URI'][:50]}...")
            
            # Check jobs
            jobs = Job.query.limit(5).all()
            print(f"📊 Found {len(jobs)} jobs in database:")
            for job in jobs:
                print(f"   🏗️  ID: {job.id} - {job.title} - {job.location}")
            
            # Check users  
            users = User.query.limit(5).all()
            print(f"👥 Found {len(users)} users:")
            for user in users:
                print(f"   👤 ID: {user.id} - {user.first_name} {user.last_name} ({user.role})")
            
            # Check categories
            categories = Category.query.limit(5).all()
            print(f"🏗️  Found {len(categories)} categories:")
            for cat in categories:
                print(f"   📋 {cat.name} - {cat.whs_risk_level}")
            
            if jobs and users:
                print("✅ Database has data - ready for real contract generation!")
                
                # Try generating a contract with real data
                job = jobs[0]
                contractor = User.query.filter_by(role='contractor').first() or users[0]
                worker = User.query.filter_by(role='worker').first() or (users[1] if len(users) > 1 else users[0])
                
                print(f"\n🧪 Testing contract generation:")
                print(f"   Job: {job.title}")
                print(f"   Contractor: {contractor.first_name} {contractor.last_name}")
                print(f"   Worker: {worker.first_name} {worker.last_name}")
                
                # Create dummy application
                class DummyApp:
                    def __init__(self):
                        self.id = 999
                
                app_data = DummyApp()
                
                # Test contract generation
                generator = ContractGenerator()
                
                try:
                    # Check if job has hourly_rate field
                    if hasattr(job, 'hourly_rate') and job.hourly_rate:
                        contract_data = generator.generate_contract_data(job, contractor, worker, app_data)
                        filename = f"real_contract_{job.id}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.html"
                        filepath = generator.save_contract_html(contract_data, filename)
                        
                        print(f"✅ REAL CONTRACT GENERATED: {filepath}")
                        print(f"💰 Rate: ${contract_data['hourly_rate']}/hour")
                        return filepath
                    else:
                        print("❌ Job missing hourly_rate field")
                        print(f"   Available fields: {[c.name for c in job.__table__.columns]}")
                        
                        # Try using budget fields as backup
                        if hasattr(job, 'budget_min') and job.budget_min:
                            print(f"💡 Using budget range: ${job.budget_min} - ${job.budget_max}")
                            # Could calculate hourly rate from budget
                        
                except Exception as e:
                    print(f"❌ Contract generation error: {e}")
                    
            else:
                print("❌ Database is empty - need to create some test data")
                
    except ImportError as e:
        print(f"❌ Import error: {e}")
        print("💡 Make sure you're running from the workspace root directory")
    except Exception as e:
        print(f"❌ Database connection error: {e}")
        print("💡 Check your PostgreSQL connection")


def create_test_data():
    """Create some test data in your PostgreSQL database"""
    import sys
    import os
    
    project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    sys.path.insert(0, project_root)
    
    try:
        from app import create_app
        from app.models import Job, User, Category
        from app.extensions import db
        
        app = create_app()
        
        with app.app_context():
            # Check if we have categories
            category_count = Category.query.count()
            if category_count == 0:
                print("❌ No categories found - run populate_categories.py first")
                return
            
            # Create test contractor
            contractor = User.query.filter_by(role='contractor').first()
            if not contractor:
                contractor = User(
                    email='test.contractor@rateright.com',
                    first_name='John',
                    last_name='Builder',
                    role='contractor',
                    phone_number='0412345678',
                    location='Sydney, NSW',
                    abn_number='12345678901'
                )
                contractor.set_password('password123')
                db.session.add(contractor)
            
            # Create test worker
            worker = User.query.filter_by(role='worker').first()
            if not worker:
                worker = User(
                    email='test.worker@rateright.com',
                    first_name='Mike',
                    last_name='Carpenter',
                    role='worker',
                    phone_number='0487654321',
                    location='Parramatta, NSW',
                    abn_number='98765432109'
                )
                worker.set_password('password123')
                db.session.add(worker)
            
            # Create test job
            job_count = Job.query.count()
            if job_count == 0:
                category = Category.query.first()
                job = Job(
                    title='Test Carpentry Job',
                    description='Build custom kitchen cabinets for residential project',
                    contractor_id=contractor.id,
                    category_id=category.id,
                    location='Parramatta, NSW',
                    budget_min=800,
                    budget_max=1200,
                    status='open',
                    white_card_required=True,
                    insurance_required=True
                )
                db.session.add(job)
            
            db.session.commit()
            print("✅ Test data created successfully!")
            
    except Exception as e:
        print(f"❌ Error creating test data: {e}")


if __name__ == "__main__":
    print("🔧 Testing Contract Generator...")
    print("=" * 50)
    
    # Test with dummy data first
    print("1️⃣ Testing with dummy data:")
    test_contract_generation()
    
    print("\n2️⃣ Testing with real PostgreSQL database:")
    test_with_real_database()
