#!/usr/bin/env python3
"""Seed weekly plan demo data for Time Sheet V2."""
import odoo
from datetime import date, timedelta


def monday_of(day):
    return day - timedelta(days=day.weekday())


odoo.tools.config.parse_config(['-d', 'testing'])
registry = odoo.registry('testing')

with registry.cursor() as cr:
    env = odoo.api.Environment(cr, odoo.SUPERUSER_ID, {})
    Plan = env['timesheet.v2.week.plan']
    admin = env.ref('base.user_admin')
    employee = env['hr.employee'].search([('user_id', '=', admin.id)], limit=1)
    if not employee:
        cr.commit()
        print('No employee linked to admin — skip.')
        raise SystemExit(0)

    wca = env.ref('jb_timesheet_v2.demo_partner_wca', raise_if_not_found=False)
    internal = env.ref('jb_timesheet_v2.demo_partner_internal', raise_if_not_found=False)
    project_wca = env.ref('jb_timesheet_v2.demo_project_wca_portal', raise_if_not_found=False)
    project_internal = env.ref('jb_timesheet_v2.demo_project_internal_admin', raise_if_not_found=False)

    this_monday = monday_of(date.today())
    last_monday = this_monday - timedelta(days=7)

    current = Plan.get_or_create_week(employee, this_monday)
    if not current.line_ids:
        current.write({'line_ids': [
            (0, 0, {
                'partner_id': wca.id if wca else False,
                'project_id': project_wca.id if project_wca else False,
                'name': 'IPW portal dev — sprint tasks',
                'planned_hours': 10.0,
            }),
            (0, 0, {
                'partner_id': internal.id if internal else False,
                'project_id': project_internal.id if project_internal else False,
                'name': 'Admin, planning, team sync',
                'planned_hours': 5.0,
            }),
            (0, 0, {
                'partner_id': wca.id if wca else False,
                'project_id': project_wca.id if project_wca else False,
                'name': 'Client status meeting prep',
                'planned_hours': 2.0,
            }),
        ]})

    previous = Plan.get_or_create_week(employee, last_monday)
    if not previous.line_ids:
        previous.write({'line_ids': [
            (0, 0, {
                'partner_id': wca.id if wca else False,
                'project_id': project_wca.id if project_wca else False,
                'name': 'Portal bug fixes',
                'planned_hours': 8.0,
                'is_done': True,
            }),
            (0, 0, {
                'partner_id': internal.id if internal else False,
                'project_id': project_internal.id if project_internal else False,
                'name': 'Weekly reporting',
                'planned_hours': 3.0,
                'is_done': True,
            }),
        ]})

    cr.commit()
    print('Seeded weekly plans: current=%s hrs, previous=%s hrs' % (
        current.total_planned_hours,
        previous.total_planned_hours,
    ))
